GDI+位图透明

分享.NETGDI+ by 达达 at 2006-04-26

前段时间做了一个图片透明画的代码,基本思路是使用ColorMatrix设置位图的Alpha通道,使其透明化。这类代码可能高手都懒得写,像我等菜鸟要用时就得费一番周则研究了,所以我把做完的代码发上来,大家有需要用的就拿去用,如果高兴的话还可以评论里说声加油之类的话,呵呵。

利用ColorMatrix还可以调整整个位图的RGB值,看各位需要发挥了。

代码如下:

//// 
/// 改变图像透明度(真透明)
/// 
/// 所要转变的图像
/// 透明度,最大为1,最小为0
/// 改变后的图像
public static Bitmap VitrificationImage(Image img, float alpha)
{
    Bitmap _newImg = new Bitmap(img.Width, img.Height);

    using (Graphics _g = Graphics.FromImage(_newImg))
    {
        using (ImageAttributes _imageAttrs = new ImageAttributes())
        {
            _imageAttrs.SetColorMatrix(new ColorMatrix(CreateAlphaMatrix(alpha)));

            _g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height),
                        1, 1, img.Width, img.Height, GraphicsUnit.Pixel, _imageAttrs);
        }
    }

    return _newImg;
}

//// 
/// 创建用于改变图像透明度的颜色矩阵
/// 
/// 所要设置的透明度
/// 返回用于图像转换的颜色矩阵
private static float[][] CreateAlphaMatrix(float alpha)
{
    if (alpha > 1)
        alpha = 1;

    if (alpha < 0)
        alpha = 0;

    float[][] _matrix =
    { 
                new float[] {1, 0, 0, 0, 0},
                new float[] {0, 1, 0, 0, 0},
                new float[] {0, 0, 1, 0, 0},
                new float[] {0, 0, 0, alpha, 0},
                new float[] {0, 0, 0, 0, 1}
    };

    return _matrix;
}