C#中使用ColorMatrix修改图像透明度不生效问题求助
问题根因
你的代码逻辑存在两处核心问题导致透明度调整不生效:
- 初始化
newImage时直接通过new Bitmap(sourceImage)完整复制了原图的所有像素作为底层,该底层本身是不透明的。后续在其上方绘制半透明版本的原图,相当于在不透明的背景上叠加半透同款内容,视觉上自然不会有透明度变化。 - 若未显式指定新位图的像素格式,系统可能默认使用不带Alpha通道的格式,导致透明信息在绘制时被丢弃。
修正后可用代码
using System.Drawing; using System.Drawing.Imaging; public static Image DisableImage(Image sourceImage) { // 新建带Alpha通道的空位图,而非直接复制原图 Bitmap newImage = new Bitmap(sourceImage.Width, sourceImage.Height, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(newImage)) { // 清空画布为完全透明 g.Clear(Color.Transparent); using (ImageAttributes imageAttributes = new ImageAttributes()) { ColorMatrix colorMatrix = new ColorMatrix(); // 设置Alpha通道缩放为0.5 colorMatrix.Matrix33 = 0.5f; imageAttributes.SetColorMatrix(colorMatrix); // 将半透明的原图绘制到透明画布上 g.DrawImage(sourceImage, new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), 0, 0, sourceImage.Width, sourceImage.Height, GraphicsUnit.Pixel, imageAttributes); } } return newImage; }
补充说明
如果需要在WinForm等桌面平台的控件上渲染这张半透明图像,需要确保对应控件的背景样式支持透明渲染,例如将PictureBox、Button等控件的BackColor属性设置为Transparent。
内容的提问来源于stack exchange,提问作者JohnSaps
相关产品推荐
相关产品推荐

