SkiaSharp 剪切路径

Jak*_*fer 1 .net c# .net-core skiasharp

我正在使用 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我还看了微软的这个文档。它显示了使用路径进行剪切,但我还无法使其正常工作。

总之:我正在寻找一种方法,使图像/画布的所有图层在某些区域透明。

任何帮助是极大的赞赏!:D

Mat*_*hew 5

我认为你可以通过设置来做到这一点SPaint.BlendMode = SKPaintBlendMode.Src。这意味着当画布绘制时,它只需要使用源颜色,并替换现有的颜色。

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

你实际上在做什么

canvas.DrawPath(path, new SKPaint { Color = SKColors.Transparent});
Run Code Online (Sandbox Code Playgroud)

拿起画笔,将其浸入透明颜料中,然后进行绘画。所以你什么也看不见。油漆是透明的。

但是,您更想做的是在绘制之前进行剪辑:

https://learn.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));
Run Code Online (Sandbox Code Playgroud)