8

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

Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
Sreenath
  • 81
  • 1
  • 1
  • 2

5 Answers5

9

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.

Jeremiah Morrill
  • 4,248
  • 2
  • 17
  • 21
2

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

John K
  • 28,441
  • 31
  • 139
  • 229
  • Without using the WinForms is there is any way to use GDI+ drawing by using System::Drawing::Graphics class? – Sreenath Oct 22 '09 at 06:34
2

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

Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
1

@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();
TheCloudlessSky
  • 18,608
  • 15
  • 75
  • 116
  • 3
    What's the `Gdi` namespace? It looks like you have aliased `System.Drawing` to `Gdi (i.e. using Gdi = System.Drawing)` - can you confirm? – RB. Nov 11 '14 at 14:01
  • 5
    Aliasing System.Drawing to Gdi in this example is a pretty bad idea since you can't just copy and paste the code and it also adds more confusion for readers. – CyberFox May 20 '16 at 02:57
  • Is there a reason for aliasing the namespace? Does Bitmap have other implementations? – Gregory William Bryant Jul 07 '20 at 11:38
-4

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.

Alastair Pitts
  • 19,423
  • 9
  • 68
  • 97