How to use GDI + drawing in WPF?

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

+6
wpf gdi + graphics
source share
5 answers

There are several ways to do this, the simplest would be to block your Bitmap, which you control with GDI, to get a pixel buffer (Scan0 IntPtr in BitmapData, which you get from blocking). CopyMemory (...) from your pixel buffer to WriteableBitmap.BackBuffer .

There are more efficient ways in WPF, for example, using InteropBitmap instead of WriteableBitmap. But this requires more p / invoke.

+9
source share

Try building the Windows Form custom element in the WPF project and encapsulate the GDI + drawing into it. See Walkthrough: Hosting a Windows Forms User Control Using WPF Designer

+1
source share

WPF comes with new graphics features, you can explore it here , but if you want to use the old GDI + API, one way to do this is to create a Winform draw and place it in WPF

+1
source share

@Jeremiah Morrill is what you do at the core. However, Microsoft was good enough to provide some interaction 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(); 
+1
source share

This is usually a bad idea. WPF is a completely new API, and mixing in GDI + can lead to poor performance, memory leaks, and other unwanted things.

-4
source share

All Articles