smourier / DirectN

Direct interop Code for .NET Framework, .NET Core and .NET 5+ : DXGI, WIC, DirectX 9 to 12, Direct2D, Direct Write, Direct Composition, Media Foundation, WASAPI, CodecAPI, GDI, Spatial Audio, DVD, Windows Media Player, UWP DXInterop, WinUI3, etc.
MIT License
311 stars 28 forks source link

Example for using a geometric mask to clip a region #30

Closed d2phap closed 1 year ago

d2phap commented 1 year ago

Hi @smourier,

I'm following this tutorial: https://learn.microsoft.com/en-us/windows/win32/direct2d/how-to-clip-with-layers to create an inverted rectangle for selection. But it does not work due to the D2D1_LAYER_PARAMETERS is not valid.

My code is as below:

var selection = new D2D_RECT_F(0, 0, 200, 100);
var rectGeo = _d2dFactory.CreateRectangleGeometry(selection);

var lp = new D2D1_LAYER_PARAMETERS()
{
  geometricMask = rectGeo.StructureToPtr(),
  maskAntialiasMode = D2D1_ANTIALIAS_MODE.D2D1_ANTIALIAS_MODE_PER_PRIMITIVE,
};

_renderTarget.BeginDraw();

_renderTarget.PushLayer(lp);
_renderTarget.DrawBitmap(...);
_renderTarget.FillRectangle(...);
_renderTarget.PopLayer();

_renderTarget.EndDraw();

And this is what I want to draw:

image

Thank you!

smourier commented 1 year ago

Hi,

If _d2dFactory is a IComObject<ID2D1Factory1> then, it's not a structure, but a wrapper on a COM object, so you can get an IntPtr (a COM reference pointer) from it with a code like this:

var ptr = Marshal.GetIUnknownForObject(rectGeo.Object);
d2phap commented 1 year ago

Thank you! I forgot this 😅