How to create a transparent bitmap in Direct2D

女生的网名这么多〃 提交于 2021-02-07 08:22:35

问题


I need to create a transparent bitmap using Direct2D and draw, by using my device context, on it.

ID2D1DeviceContext1* d2dContext = ...
ID2D1Bitmap* pBitmap;

d2dContext->CreateBitmap(
    bitmapSize,
    nullptr,
    0,
    D2D1::BitmapProperties1(
        D2D1_BITMAP_OPTIONS_TARGET,
        D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
        dpiX, dpiY),
    &pBitmap);

d2dContext->BeginDraw();
d2dContext->SetTarget(pBitmap);
d2dContext->Clear(D2D1::ColorF(0, 0));
d2dContext->DrawLine(...);
hr = d2dContext->EndDraw();

Unfortunately I am not able to create any transparent bitmaps. I tried with several pixel format combinations, including D2D1_ALPHA_MODE_STRAIGHT, but without succeeding.

Is there any solution?


回答1:


Good news Nick: You are creating transparent bitmaps, however the reason why you are not seeing your expected results has to do with window creation. Kenny Kerr demonstrated proper layered window creation with Direct2D back in 2009 here.

Since then much has changed with respect to windows rendering, with Win8 and Win10 using a composition engine, and allowing developers access to the DirectComposition API. As a result, Kenny Kerr provided an updated article in 2014 on the topic.

My recent projects required Win7 support, so I personally stick with pure Direct2D.

EDIT: And of course ensure your render target is properly created. Hope this helps.




回答2:


Here is what I do in Sciter when I need to create cached rendering (bitmap) :

ID2D1RenderTarget* src = ...
d2d::asset<ID2D1BitmapRenderTarget> dst = nullptr;

// creating temp surface - compatible render target:
src->CreateCompatibleRenderTarget(sz,dst.target());

dst->BeginDraw();
dst->Clear(init_color);

... drawing on that temp surface ...
dst->EndDraw();

d2d::asset<ID2D1Bitmap> dst_bmp;
hr = dst->GetBitmap(il->d2d_bmp.target());

return dst_bmp;

This method delegates bitmap creation to the ID2D1RenderTarget and so that bitmap will always be compatible with source. The code is used with transparent init_color's mostly.

I wouldn't use SetTarget() as it is not clear what it does with clips, etc.



来源:https://stackoverflow.com/questions/39900556/how-to-create-a-transparent-bitmap-in-direct2d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!