How to use the GDI+ drawing in WPF?

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

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

相关标签:
5条回答
  • 2021-01-05 13:30

    There are several ways to do this, the easiest would be to lock your Bitmap you manipulated with GDI, get the pixel buffer (Scan0 IntPtr in the BitmapData you get from the lock). CopyMemory(...) from you pixel buffer to a WriteableBitmap.BackBuffer.

    There are more performant ways in WPF, like using the InteropBitmap instead of WriteableBitmap. But that needs more p/invoke.

    0 讨论(0)
  • 2021-01-05 13:33

    Try compositing a Windows Form User Control in your WPF project and encapsulate GDI+ drawing in it. See Walkthrough: Hosting a Windows Forms User Control by Using the WPF Designer

    0 讨论(0)
  • 2021-01-05 13:36

    This is generally a bad idea. WPF is a completely new API and mixing in GDI+ may result in poor performance, memory leaks and other undesirable things.

    0 讨论(0)
  • 2021-01-05 13:45

    WPF comes with new graphics features, you can investigate it here, but if you want to use an old GDI+ API one way to do is to create Winform draw there and host it into WPF

    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题