If ask Internet about how to “load PNG from resource” it gives in return a lot of examples using a bunch of code. We can use some stuff found there, but once using MFC and enabling Direct2D support, that becomes easier: just have to construct and create a CD2DBitmap object, passing the resource ID and the resource type.
Here is an example:
Create a CD2DBitmap object from a PNG resource
1 2 3 4 5 6 7 8 9 |
HRESULT CSomeWindow::LoadDemoImage(CHwndRenderTarget* pRenderTarget) { // Load Direct2D bitmap from "PNG" resource m_pBitmamLogo = new CD2DBitmap(pRenderTarget, IDB_PNG_DEMO, // resource ID _T("PNG")); // resource type return m_pBitmamLogo->Create(pRenderTarget); } |
It’s also possible to easily load a Direct2D brush.
Create a CD2DBitmapBrush object from a PNG resource
1 2 3 4 5 6 7 8 9 10 11 12 |
HRESULT CSomeWindow::LoadDemoBrush(CHwndRenderTarget* pRenderTarget) { // Load Direct2D brush from "PNG" resource m_pBrushBackground = new CD2DBitmapBrush(pRenderTarget, IDB_PNG_DEMO, // resource ID _T("PNG"), // resource type CD2DSizeU(0, 0), &D2D1::BitmapBrushProperties(D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP)); return m_pBrushBackground->Create(pRenderTarget); } |
Notes
- Loading PNG is just an example. We can load other WIC-supported formats (includes “standard” formats like JPEG, TIFF etc. and other graphic formats which have a WIC decoder installed).
- To see how to enable Direct2D support and further render the loaded images, see the previous articles and/or have a look in the demo application attached here.
Demo application
Download: PNG Resource Loading Demo.zip (1178)
You’re leaking, horribly. Even if the render target is supposed to delete stuff, it has a high probability of leaking and will terminate when the API is used correctly – with references to objects allocated on the stack.
The demo project, as it is, has no leaks. CRenderTarget doesn’t just suppose but cleans the stuff. However you’re right… if, let’s say, someone simply copy/pastes _LoadBackgroundBrush then calls it repeatedly, things may become horrible. 🙂
I’ll do an update, asap.
Thank you for the feedback!