Search code examples
skiasharp

SkiaSharp draw reversible shapes


Is there a way to draw reversible shapes with SkiaSharp?

With reversible I mean outColor = srcColor XOR dstColor, so when you draw over same color again, the original color is restored. Like in WinForms ControlPaint.DrawReversibleFrame or (old) Windows FocusRects.

I'm using SkiaSharp 2.88.0


Solution

  • You can use Exclusion blend mode when drawing, for example:

    // draw some random image on canvas
    var bitmap = SKBitmap.Decode(@"random.jpg");
    var info = new SKImageInfo(256, 256);
    using var surf = SKSurface.Create(info);
    var canvas = surf.Canvas;
    canvas.DrawBitmap(bitmap, info.Rect);
    
    // initialize paint with Exclusion blend mode
    var paint = new SKPaint {
        Color = SKColors.Yellow,
        Style = SKPaintStyle.Fill,
        BlendMode = SKBlendMode.Exclusion
    };
    
    // draw overlapping rectangles using the paint
    canvas.DrawRect(10, 10, 50, 50, paint);
    canvas.DrawRect(25, 25, 50, 50, paint);
    

    Result image:

    Result image