GDI + Bug:抗锯齿白色透明度

时间:2013-04-11 18:43:57

标签: c# gdi+ transparent antialiasing

以下代码将创建一个透明位图,然后在其上绘制一个带有抗锯齿的白色椭圆。

using(var background = new Bitmap(500, 500))
using (var graphics = Graphics.FromImage(background))
{
    graphics.SmoothingMode = SmoothingMode.AntiAlias;

    graphics.Clear(Color.Transparent);

    graphics.DrawEllipse(new Pen(Color.White, 50), 250, 250, 150, 150);

    background.Save("test.png", ImageFormat.Png);
 }

我发现的错误是椭圆边缘周围的抗锯齿像素有一个意想不到的颜色。它们的RGB值为(254,254,254)而不是(255,255,255)。由于GDI +将透明定义为ARGB(0,255,255,255),白色定义为(255,255,255,255),为什么我在混合后看到254?

1 个答案:

答案 0 :(得分:0)

我在Mono(Mac OS X)中从SVG生成PNG时遇到了同样的问题,但由于某种原因不在Windows上。

为了解决这个问题,我将最近的rgb值从图中复制到抗锯齿像素,但保留了antialias-alpha值。

代码基于以下示例:https://msdn.microsoft.com/en-us/library/ms229672(v=vs.90).aspx

在save方法之前作为最后一步运行的代码:

var pxf = PixelFormat.Format32bppArgb;
var rect = new Rectangle(0, 0, image.Width, image.Height);
BitmapData bmpData = image.LockBits(rect, ImageLockMode.ReadWrite, pxf);

IntPtr ptr = bmpData.Scan0;

int numBytes = image.Width * image.Height * 4;
byte[] rgbValues = new byte[numBytes];
Marshal.Copy(ptr, rgbValues, 0, numBytes);

for (int argb = 0; argb < rgbValues.Length; argb += 4) {
    var a = rgbValues [argb + 3]; //A
    if(a > 0x00 && a < 0xFF) { //Antialiasing:
        //Scan for neares solid with 0 transparency:
        for (int i = 0; i < 3; i++) { //3 pixels scan seems to be enough

            var right = argb + i * 4;
            var left = argb - i * 4;
            var up = argb - i * image.Width * 4;
            var down = argb + i * image.Width * 4;

            if (right < rgbValues.Length && rgbValues [right + 3] == 0xFF) {
                rgbValues [argb+2] = rgbValues [right + 2]; //R
                rgbValues [argb+1] = rgbValues [right + 1]; //G
                rgbValues [argb] = rgbValues [right];       //B
                break;
            } else if (left > 0 && rgbValues [left + 3] == 0xFF) {
                rgbValues [argb+2] = rgbValues [left + 2];
                rgbValues [argb+1] = rgbValues [left + 1];
                rgbValues [argb] = rgbValues [left];
                break;
            } else if (up > 0 && rgbValues [up + 3] == 0xFF) {
                rgbValues [argb+2] = rgbValues [up + 2];
                rgbValues [argb+1] = rgbValues [up + 1];
                rgbValues [argb] = rgbValues [up];
                break;
            } else if (down < rgbValues.Length && rgbValues [down + 3] == 0xFF) {
                rgbValues [argb+2] = rgbValues [down + 2];
                rgbValues [argb+1] = rgbValues [down + 1];
                rgbValues [argb] = rgbValues [down];
                break;
            }
        }
        //rgbValues [argb+3] = a; //Keep old alpha.
    }
}

Marshal.Copy(rgbValues, 0, ptr, numBytes);

image.UnlockBits(bmpData);

`