I need to display a Windows Metafile (EMF) using WPF, how can I do?
I'd to keep the image vector-based.
Here is a utility function that loads an EMF file and converts it into a WPF BitmapSource:
public static class Emfutilities
{
public static BitmapSource ToBitmapSource(string path)
{
using (System.Drawing.Imaging.Metafile emf = new System.Drawing.Imaging.Metafile(path))
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(emf.Width, emf.Height))
{
bmp.SetResolution(emf.HorizontalResolution, emf.VerticalResolution);
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
{
g.DrawImage(emf, 0, 0);
return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}
}
}
}
You simply use it like this:
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// img is of Image type for example
img.Source = Emfutilities.ToBitmapSource("SampleMetafile.emf");
}
}
}
The drawback is you will need to reference System.Drawing.dll (GDI+) into your WPF application, but that should not be a big issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With