How do I clear a Direct2D render target to fully transparent

前端 未结 3 1282
梦毁少年i
梦毁少年i 2020-12-11 05:06

I\'m trying to draw semi-transparent rectangles on an invisible HWND. However, clearing the window with ID2D1HwndRenderTarget::Clear just makes the entire w

相关标签:
3条回答
  • 2020-12-11 05:46

    Use ID2D1DCRendTarget instead of ID2D1HwndRendTarget, then bind the device context (DC) of your window before drawing begins.

    Of course, you need to set the WS_EX_LAYERED for your window and then call SetLayeredWindowAttributes to set the transparent color:

    SetLayeredWindowAttributes(hWnd, RGB(0, 0, 0), 0, LWA_COLORKEY);
    

    Screenshot:

    0 讨论(0)
  • 2020-12-11 05:48

    When creating your RenderTarget, you'll have to tell D2D that you want to use alpha (in premultiplied mode) in the pixel format:

      HRESULT hr = mD2DFactory->CreateHwndRenderTarget(
        D2D1::RenderTargetProperties( D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat( DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED ) ),
        D2D1::HwndRenderTargetProperties( mWindow, size ),
        &mRenderTarget );
    

    After this, calling Clear() with an alpha value of zero works just fine.

    0 讨论(0)
  • 2020-12-11 05:55

    Transparency is a problem. The only window that support per-pixel transparency are WS_EX_LAYERED windows. These windows were designed for uses like drag-drop icons, and that leads to problems in every other usage.

    Using D2D with WS_EX_LAYERED windows requires that you use a DXGI render target. To EndDraw, you get a DC out of the render target then pass that into the layered window and tell the layered window to update itself. (Try this with a HWNDRenderTarget - it will probably crash the device driver).

    I suspect your window appears transparent because it's not drawing at all.

    Another gotcha you may run into... if the window is sufficiently transparent, mouse clicks will go through it to the underlying window.

    0 讨论(0)
提交回复
热议问题