How to use the GDI+ drawing in WPF?

后端 未结 5 1896
盖世英雄少女心
盖世英雄少女心 2021-01-05 13:20

I want to use the GDI+ drawing in my WPF control.

5条回答
  •  有刺的猬
    2021-01-05 13:45

    @Jeremiah Morrill's solution is what you'd do at the core. However, Microsoft was nice enough to provide some interop methods:

    using System.Windows.Interop;
    using Gdi = System.Drawing;
    
    using (var tempBitmap = new Gdi.Bitmap(width, height))
    {
        using (var g = Gdi.Graphics.FromImage(tempBitmap))
        {
            // Your GDI drawing here.
        }
    
        // Copy GDI bitmap to WPF bitmap.
        var hbmp = tempBitmap.GetHbitmap();
        var options = BitmapSizeOptions.FromEmptyOptions();
        this.WpfTarget.Source = Imaging.CreateBitmapSourceFromHBitmap(hbmp,
            IntPtr.Zero, Int32Rect.Empty, options);
    }
    
    // Redraw the WPF Image control.
    this.WpfTarget.InvalidateMeasure();
    this.WpfTarget.InvalidateVisual();
    

提交回复
热议问题