WPF 对控件截图

 

image

突然需要一个Logo,找又找不到,就自己做喽,首先想到的是ps,简单方便,转念一想,wpf搞这个不是很简单么?直接弄做好,截图一下不就行了。。。

开工了,先在iconfont上找了个图标:

image

是这样的

然后取名:WPF开发者

然后新建一个工程,主界面就是这样了:

image

点击截图按钮 ,对包含图标和字体的Grid截图,保存成png,透明背景的哦

窗体代码:

<Window x:Class="WPFDemos.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPFDemos"
        mc:Ignorable="d"
        x:Name="widnow"
        WindowStartupLocation="CenterScreen"
        UseLayoutRounding="True"
        Title="截图示例" Height="300" Width="500">
    <Grid>
        <Grid x:Name="target" HorizontalAlignment="Center" VerticalAlignment="Center" Background="Transparent">
            <StackPanel Orientation="Horizontal" Margin="5 0" >
                <Image x:Name="str" Width="32" Height="32" Source="/Images/vs32.png" Margin="5 0"/>
                <TextBlock Text="WPF开发者" VerticalAlignment="Center" Foreground="#CFCEDC" 
                           FontSize="25" FontWeight="Bold" FontFamily="微软雅黑"/>
            </StackPanel>
        </Grid>
        <Button HorizontalAlignment="Right" VerticalAlignment="Center" Foreground="White" Padding="10" Click="Button_Click" Background="Transparent" Margin="50" Content="截图"/>
    </Grid>
</Window>

窗体后台代码:

using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace WPFDemos
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext context = drawingVisual.RenderOpen())
            {
                VisualBrush brush = new VisualBrush(target) { Stretch = Stretch.None };
                context.DrawRectangle(brush, null, new Rect(0, 0, target.ActualWidth, target.ActualHeight));
                context.Close();
            }
            RenderTargetBitmap targetBitmap = new RenderTargetBitmap((int)target.ActualWidth, (int)target.ActualHeight, 96d, 96d, PixelFormats.Default);
            targetBitmap.Render(drawingVisual);
            PngBitmapEncoder saveEncoder = new PngBitmapEncoder();
            saveEncoder.Frames.Add(BitmapFrame.Create(targetBitmap));
            string tempFile = $"d:\\test.png";
            System.IO.FileStream fs = System.IO.File.Open(tempFile, System.IO.FileMode.OpenOrCreate);
            saveEncoder.Save(fs);
            fs.Close();
        }
    }
}

截图后,保存在D盘,截出来是这样的

image

 

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情

    暂无评论内容