Arsen Zahray
Arsen Zahray

Reputation: 25287

Load and draw png with Direct2D

I am getting started with using Direct2D with c#.

I've downloaded and used this example app.

The application works fine, but I also need it to load png images from the hard drive and display them.

In the sample, this would be done in the function OnRender, probably with RenderTarget.DrawBitmap.

However, I'm having a problem with actually loading png into memory. I understand I should use something like WICImagingFactory for it, but I can't find the class and I'm not sure how to use it to get the D2DBitmap object that is required by RenderTarget.DrawBitmap

Can anyone provide a c# example how to load image into Direct2D?

Upvotes: 1

Views: 2184

Answers (1)

Arsen Zahray
Arsen Zahray

Reputation: 25287

I ended up with using SharpDX.

Here's a good example how to load image with SharpDX: https://english.r2d2rigo.es/2014/08/12/loading-and-drawing-bitmaps-with-direct2d-using-sharpdx/

ImagingFactory imagingFactory = new ImagingFactory();
NativeFileStream fileStream = new NativeFileStream(@"D:\path\myfile.png",
    NativeFileMode.Open, NativeFileAccess.Read);

BitmapDecoder bitmapDecoder = new BitmapDecoder(imagingFactory, fileStream, DecodeOptions.CacheOnDemand);
BitmapFrameDecode frame = bitmapDecoder.GetFrame(0);

FormatConverter converter = new FormatConverter(imagingFactory);
converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA);

newBitmap = SharpDX.Direct2D1.Bitmap1.FromWicBitmap(target, converter); 

target.DrawBitmap(newBitmap,new RawRectangleF(0,0,target.Size.Width,target.Size.Height),1,BitmapInterpolationMode.Linear );

Also, in case you want to do the whole program with SharpDX (so you don't end up using 2 different semi-incompatible frameworks), here's a working example how this can be done: https://github.com/dalance/D2dControl

Upvotes: 2

Related Questions