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

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;
        }
    }
}




posted @   JohnYang819  阅读(319)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2021-11-13 # C#之异步
点击右上角即可分享
微信分享提示