SkiaSharp 切出路径

SkiaSharp cut out path

我正在使用 System.Drawing 进行一些图像编辑,现在将所有内容移植到 SkiaSharp,以便在 Linux / .NET Core 上使用它。一切正常,除了我还没有找到以编程方式给图像圆角的方法。

我写了一些依赖于以圆形形式绘制路径的代码,然后尝试将路径的外部着色为透明。但是这不起作用,因为它似乎有多个层,并且使上层的部分透明不会使图像的整个区域(所有层)透明。这是我的代码:

public static SKBitmap MakeImageRound(SKBitmap image)
{
    SKBitmap finishedImage = new SKBitmap(image.Width, image.Height);

    using (SKCanvas canvas = new SKCanvas(finishedImage))
    {
       canvas.Clear(SKColors.Transparent);
       canvas.DrawBitmap(image, new SKPoint(0, 0));
       SKPath path = new SKPath();
       path.AddCircle(image.Width / 2, image.Height / 2, image.Width / 2 - 1f);
       path.FillType = SKPathFillType.InverseEvenOdd;
       path.Close();
       canvas.DrawPath(path, new SKPaint {Color = SKColors.Transparent, Style = SKPaintStyle.Fill });
       canvas.ResetMatrix();              
       return finishedImage;
    }
}

如果这是错误的代码,我很抱歉,这是我第一次使用 C# 进行图像编辑,因此我也是 SkiaSharp 的绝对初学者。我修改了从 here.

获得的 System.Drawing 代码

这个我也看了Microsoft document。它显示了使用路径的裁剪,但我还没有能够让它工作。

所以总而言之:我正在寻找一种方法,使 image/the canvas 的所有层在某些区域透明。

非常感谢任何帮助! :D

我想你可以通过设置 SPaint.BlendMode = SKPaintBlendMode.Src 来做到这一点。这意味着当 canvas 正在绘制时,它必须使用源颜色,并替换现有颜色。

https://docs.microsoft.com/dotnet/api/skiasharp.skpaint.blendmode

你实际上在做什么

canvas.DrawPath(path, new SKPaint { Color = SKColors.Transparent});

正在拿起画笔,蘸上透明颜料,开始画画。所以你什么也看不见。油漆很透明。

但是,你更想做的是剪辑before绘图:

https://docs.microsoft.com/dotnet/api/skiasharp.skcanvas.clippath

canvas.Clear(SKColors.Transparent);

// create the circle for the picture
var path = new SKPath();
path.AddCircle(image.Width / 2, image.Height / 2, image.Width / 2 - 1f);

// tell the canvas not to draw outside the circle
canvas.ClipPath(path);

// draw the bitmap
canvas.DrawBitmap(image, new SKPoint(0, 0));