• 把wpf的窗体保存为png图片


    昨晚在stack  overflow刷问题时看到有这个问题,今天早上刚好来尝试学习一下

    stack overflow的链接如下:

    c# - How to render a WPF UserControl to a bitmap without creating a window - Stack Overflow

    测试步骤如下:

    1  新建.net framework 3.5的wpf窗体程序

    2 默认的窗体的xaml代码如下:

    1. "WpfDemo.MainWindow"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    6. xmlns:local="clr-namespace:WpfDemo"
    7. xmlns:s="clr-namespace:System;assembly=mscorlib"
    8. mc:Ignorable="d"
    9. Title="MainWindow" Height="450" Width="800">
    10. "Left">
    11. 123455
    12. Content="确定">

    窗体效果如下:

    对应的后台代码如下:

    1. using System;
    2. using System.Collections.Generic;
    3. using System.IO;
    4. using System.Linq;
    5. using System.Text;
    6. using System.Windows;
    7. using System.Windows.Controls;
    8. using System.Windows.Data;
    9. using System.Windows.Documents;
    10. using System.Windows.Input;
    11. using System.Windows.Interop;
    12. using System.Windows.Media;
    13. using System.Windows.Media.Imaging;
    14. using System.Windows.Navigation;
    15. using System.Windows.Shapes;
    16. namespace WpfDemo
    17. {
    18. ///
    19. /// MainWindow.xaml 的交互逻辑
    20. ///
    21. public partial class MainWindow : Window
    22. {
    23. public MainWindow()
    24. {
    25. InitializeComponent();
    26. }
    27. private void BtnEnter_Click(object sender, RoutedEventArgs e)
    28. {
    29. RenderControl(this);
    30. MessageBox.Show("保存完成");
    31. }
    32. void RenderControl(Control renderControl)
    33. {
    34. RenderTargetBitmap bmp = new RenderTargetBitmap((int)renderControl.Width, (int)renderControl.Height, 0, 0, PixelFormats.Pbgra32);
    35. bmp.Render(renderControl);
    36. var encoder = new PngBitmapEncoder();
    37. encoder.Frames.Add(BitmapFrame.Create(bmp));
    38. using (Stream stm = File.Create("test.png"))
    39. encoder.Save(stm);
    40. }
    41. }
    42. }

    3  运行程序,点击确定按钮,会在bin/Debug目录下生成MainWindow窗体对应的png图片,png图片名称为test.png,如下图:

  • 相关阅读:
    Python3 输出格式美化
    golang应用专题 - channel
    Flutter Engine 编译
    【数据脱敏方案】不使用 AOP + 注解,使用 SpringBoot+YAML 实现
    蓝桥杯官网练习题(回文日期)
    数据交易是什么?看这篇文章
    (一)JDK、转义字符、数据类型
    Selenium自动化最佳实践技巧等你来学
    Lange电桥的设计
    RichView TRVStyle TextStyles
  • 原文地址:https://blog.csdn.net/zxy13826134783/article/details/134259497