使用C#替换索引图像中的颜色

时间:2011-03-21 08:47:40

标签: c# graphics gdi+

我正在使用Graphics.DrawImage将索引位图写入另一个图像。当写入“targetBitmap”

时,索引图像中的黑色应替换为透明色

如何以高效的方式执行此操作?

var graphics = Graphics.FromImage(targetBitmap);

//I want the black color in "indexBitmap" to be transparent when it's written to "targetBitmap"
graphics.DrawImage(indexedBitmap,...)

3 个答案:

答案 0 :(得分:4)

创建一个颜色贴图并将其作为“ImageAttributes”参数传递给DrawImage为我工作

var colorMaps = new[]{
   new ColorMap {OldColor = Color.FromArgb(255, 0, 0, 0), NewColor =  Color.Transparent}
};

var attr = new ImageAttributes();
attr.SetRemapTable(colorMaps);

答案 1 :(得分:1)

如何使用SetColorKey

答案 2 :(得分:0)

SetColorKey允许您在图形对象上绘制图像时选择透明背景。 但事实是,当调用SetRemapTable()函数时,这不起作用。

您也可以通过在“colorMaps”数组中添加额外的ColorMap来完成这项工作。 这个额外的ColorMap应该有 - OldColor ='选择透明色' - NewColor = Color.Transparent 然后使用扩展子调用SetRemapTable。

下面您将看到C#中的代码示例,以便轻松地将图像绘制到图形对象。 我用它来制作带图形的游戏。 此void(基本上为sub)允许您将图像绘制到图形(例如FormX.CreateGraphics())。

您可以使用其他颜色替换某些颜色,也可以选择透明颜色。

您还可以使用指定的角度(度)绘制图像。

public static void DrawImageToGraphics(Graphics gr, Bitmap img, Rectangle DestRect, Color[] OldColors, Color[] NewColors, Color TransparantColor, uint Angle)
{
    System.Drawing.Drawing2D.Matrix lmx = new System.Drawing.Drawing2D.Matrix();
    lmx.RotateAt(Angle, new PointF((DestRect.Left + DestRect.Right) / 2, (DestRect.Top + DestRect.Bottom) / 2));
    gr.Transform = lmx;

    System.Drawing.Imaging.ColorMap[] maps = new System.Drawing.Imaging.ColorMap[OldColors.Count() + 1];
    for (int i = 0; i < OldColors.Count(); i++)
    {
        maps[i].OldColor = OldColors[i];
        maps[i].NewColor = NewColors[i];
    }
    maps[OldColors.Count()].OldColor = TransparantColor;
    maps[OldColors.Count()].NewColor = Color.Transparent;
    System.Drawing.Imaging.ImageAttributes attr = new System.Drawing.Imaging.ImageAttributes();
    attr.SetRemapTable(maps);

    gr.DrawImage(img, DestRect, 0, 0, img.Width, img.Height, GraphicsUnit.Point, attr);
}
相关问题