如何在画布上绘制带有透明度/alpha通道的图像

7

你好!

这里只是简单的代码,没有包括使用等...:

var image = Image.FromFile(/* my magic source */);
var bitmap = new Bitmap(image.Width, image.Height);
var canvas = Graphics.FromImage(bitmap);
var brush = new SolidBrush(/* my magic color */);
canvas.FillRectangle(brush, 0, 0, image.Width, image.Height);
canvas.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height));
canvas.Save();
bitmap.Save(/* my magic target */);

我想在canvas上以55%透明度绘制带有透明度的.png文件image。(注意:我不想使用image.MakeTransparent() - 它已经是透明的,我只需要一些透明度效果)
请问如何实现这个功能?
1个回答

17

尝试使用ColorMatrix和ImageAttributes:

ColorMatrix cm = new ColorMatrix();
cm.Matrix33 = 0.55f;
ImageAttributes ia = new ImageAttributes();
ia.SetColorMatrix(cm);
canvas.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, ia);

8
你所使用的DrawImage重载方法不存在。我建议你使用下面这个方法: canvas.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes); - user57508
1
这种方法似乎只适用于 Rgb24 像素格式。我尝试了 Argb32 或 Indexed8bpp,但它不起作用。 - IlPADlI

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接