Skisharp ColorMatrix 反转 black/white

Skisharp ColorMatrix Invert black/white

我尝试绘制图像,在绘制第一张图像后我想反转绘图的颜色。 如果我的新方块的背景是黑色,我需要白色,如果是白色,我需要黑色。 在我的示例中,我绘制了 3 个正方形并在 x.

中偏移了 10 个像素

不幸的是,它没有产生想要的结果。

using var skBitmap = new SKBitmap(100, 40);
using var skCanvas = new SKCanvas(skBitmap);
skCanvas.Clear(SKColors.White);

var color = SKColors.Black;
float[] invertMatrix = {
    -1.0f,  0.0f,  0.0f,  0.0f,  255.0f,
    0.0f,  -1.0f,  0.0f,  0.0f,  255.0f,
    0.0f,  0.0f,  -1.0f,  0.0f,  255.0f,
    0.0f,  0.0f,  0.0f,  1.0f,  0.0f
};

using var skPaint = new SKPaint();
skPaint.Color = color;
skPaint.Style = SKPaintStyle.Fill;

skCanvas.DrawRect(10, 10, 20, 20, skPaint);

skPaint.ColorFilter = SKColorFilter.CreateColorMatrix(invertMatrix);

//move +10 in x
skCanvas.DrawRect(20, 10, 20, 20, skPaint);

//move +10 in x
skCanvas.DrawRect(30, 10, 20, 20, skPaint);

第二次调用 skCanvas.DrawRect 后,您似乎没有更新颜色。

此外,在您绘制 20 像素宽的矩形并将它们重叠时,您只需将新矩形向右移动 10 像素。

按照您想要的示例,您需要进行第 4 次调用以将颜色改回黑色,然后调用 skCanvas.DrawRect(40, 10, 20, 20, skPaint)

鉴于您要将矩形移动 10 个像素并将它们重叠,我建议您更新您的调用以生成更薄的 10 像素宽的初始矩形。

不幸的是,我找到了一个没有矩阵的解决方案。

using var skBitmap = new SKBitmap(100, 40);
using var skCanvas = new SKCanvas(skBitmap);
skCanvas.Clear(SKColors.White);

var color = SKColors.Black;

using var skPaint = new SKPaint();
skPaint.Color = color;
skPaint.Style = SKPaintStyle.Fill;

skCanvas.DrawRect(10, 10, 20, 20, skPaint);

DrawInvertRectangle(20, 10, 20, 20, skBitmap);
DrawInvertRectangle(30, 10, 20, 20, skBitmap);
private static void DrawInvertRectangle(int x, int y, int width, int height, SKBitmap skBitmap)
{
    using var skPaint = new SKPaint();
    skPaint.Color = SKColors.Black;
    skPaint.Style = SKPaintStyle.Fill;

    using var skBitmapInvert = new SKBitmap(skBitmap.Width, skBitmap.Height);
    using var skCanvas = new SKCanvas(skBitmapInvert);
    skCanvas.DrawRect(x, y, width, height, skPaint);

    for (var row = 0; row < skBitmapInvert.Height; row++)
    {
        for (var column = 0; column < skBitmapInvert.Width; column++)
        {
            var pixel = skBitmap.GetPixel(column, row);
            var pixelInvert = skBitmapInvert.GetPixel(column, row);
            if (pixelInvert.Alpha == 255 && pixelInvert.Blue == 0 && pixel.Blue == 255)
            {
                skBitmap.SetPixel(column, row, SKColors.Black);
            }
            if (pixelInvert.Alpha == 255 && pixelInvert.Blue == 0 && pixel.Blue == 0)
            {
                skBitmap.SetPixel(column, row, SKColors.White);
            }
        }
    }
}