Search code examples
win2d

Applying mask image for erasing with Win2D


I want to make transparent (erase) particular area of an image using Win2D.

For that purpose I have a mask which contains transparent colour (RRGGBBAA = xxxxxx00) for pixels that need to be erased, and white colour (RRGGBBAA = FFFFFFFF) for pixels that should stay.

Ideally, I need either CanvasBlend.And or CanvasBlend.Mutiply, but neither of those is provided with Win2D. However, there is CanvasBlend.Min, which, as I expect, should also do the job.

Here is the code:

  internal static CanvasBitmap applyMask(
        ICanvasResourceCreatorWithDpi creator,
        CanvasBitmap sourceBmp, CanvasBitmap maskBmp,
        CanvasBlend blendMode = CanvasBlend.Min) {

        var destSize = sourceBmp.Size;
        var crt = new CanvasRenderTarget(creator, destSize);
        var rect = new Rect(new Point(), destSize);

        using (var ds = crt.CreateDrawingSession()) {
             ds.Blend = CanvasBlend.SourceOver;
             ds.DrawImage(sourceBmp, rect);
             ds.Blend = blendMode;
             ds.DrawImage(maskBmp, rect);
        }

        return crt;
  }

It comes up with showing source image completely unmodified, as if masked image opacity (Alpha) is ignored. Any suggestions?


Solution

  • Take a look at the recently added AlphaMaskEffect: https://microsoft.github.io/Win2D/html/T_Microsoft_Graphics_Canvas_Effects_AlphaMaskEffect.htm