.net6.0及以上WPF中使用GDI+的demo

发布时间 2023-11-13 13:14:03作者: JohnYang819
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media.Imaging;

namespace TryDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        [DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);
        public MainWindow()
        {
            InitializeComponent();
            DrawWithGDIPlus();
        }
        private void DrawWithGDIPlus()
        {
            //install-package System.Drawing.Common
            //创建位图
            Bitmap bmp = new Bitmap(300, 200);
            using(Graphics g=Graphics.FromImage(bmp))
            {
                //创建一个画刷
                Brush brush = new SolidBrush(Color.Blue);
                //绘制矩形
                g.FillRectangle(brush, new Rectangle(50, 50, 200, 100));
                //释放资源
                brush.Dispose();
            }
            //将GDI+绘制的位图转换为WPF中的BitmapSource--------------------------------------------
            //GetHbitmap 方法是 Bitmap 类的一个方法,它会返回 GDI(图形设备接口)位图对象的句柄(HBITMAP)。
            //这个句柄是 Windows GDI 对象的一个标识符。这个方法创建一个 GDI位图对象,并返回其句柄。
            IntPtr hBitmap = bmp.GetHbitmap();
            //Imaging.CreateBitmapSourceFromHBitmap:
//Imaging.CreateBitmapSourceFromHBitmap 方法是 WPF 中的一个方法,用于创建 BitmapSource 对象,以便在WPF中显示图像。
//它接受 GDI位图对象的句柄(HBITMAP)作为输入,然后创建一个 BitmapSource 对象。
//参数解释:
//第一个参数是 hBitmap,即 GDI+位图对象的句柄。
//第二个参数是 IntPtr.Zero,用于传递对可选的色彩管理句柄的指针。在这里,我们没有使用颜色管理,所以传入了 IntPtr.Zero。
//Int32Rect.Empty 表示矩形的空区域,用于指定位图的可见区域。这里我们将其设置为空。
//BitmapSizeOptions.FromEmptyOptions() 用于指定位图大小选项,这里我们选择了空选项。
            BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
            DeleteObject(hBitmap);
            bmp.Dispose();
            System.Windows.Controls.Image image = new System.Windows.Controls.Image();
            image.Source=bitmapSource;
            this.Content = image;
        }
    }
}