Search code examples
c#.netxamarin.formsskiaskiasharp

How to avoid "adding up" of opacities in SkiaSharp


I'm currently creating a Xamarin.Forms app. One of my pages uses SkiaSharp to allow users to highlight parts of an image in a text marker style (i.e. a yellow brush with low opacity).

This is how the related SKPaint object is defined:

var strokePaint = new SKPaint()
{
    Color = Color.FromRgba(255, 255, 0, 100).ToSKColor(),
    Style = SKPaintStyle.Stroke,
    StrokeWidth = StrokeWidth
};

That's working fine so far, but what bothers me is that the opacity "increases" when I have multiple overlapping paths, until at some point the underlying picture isn't visible anymore.

What could I do to avoid this overlapping? I was thinking about merging all paths into one, but that doesn't seem to work because the user is allowed to change StrokeWidth in between strokes and I didn't see any way of drawing paths with varying width.

I hope any of you guys has some help for me. Any idea is appreciated!


Solution

  • I'm not super familiar with Skia, but I took a look at the documentation for SKPaint, and it looks like it has a BlendMode property. Based on how similar things work in other systems, that should control how colors are combined. You might have to try different values to get the effect you are looking for. Dst, or Modulate look like good candidates. – Bradley Uffner

    Thanks for your answer Bradley! I went with the Darken blend mode and set opacity to 255, which creates a very nice effect when highlighting text (only the darker color is visible, so dark text on a light background becomes dark text on a background of my marker color).