C# WinForm旋转PNG格式Bitmap时透明背景失效如何解决?
问题原因
- 你创建新的
Bitmap对象时,默认没有启用alpha通道,新建的画布背景为不透明状态,绘制透明PNG时背景会被填充为默认不透明色 Graphics对象的合成模式未设置为支持透明的模式,无法正确保留透明像素- 你当前写的
bmp.MakeTransparent()是修改原始图片,对新生成的旋转后图片完全无效,调用位置也错误
修改后的旋转方法
将你的RotateImage方法替换为如下代码即可保留透明背景:
private Bitmap RotateImage(Bitmap bmp, float angle) { // 新建Bitmap时指定支持alpha通道的像素格式,保留透明信息 Bitmap rotatedImage = new Bitmap(bmp.Width, bmp.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); rotatedImage.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution); using (Graphics g = Graphics.FromImage(rotatedImage)) { // 先将新画布清空为全透明 g.Clear(Color.Transparent); // 设置支持透明的高质量绘制参数 g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; // 原有旋转逻辑不变 g.TranslateTransform(bmp.Width / 2, bmp.Height / 2); g.RotateTransform(angle); g.TranslateTransform(-bmp.Width / 2, -bmp.Height / 2); g.DrawImage(bmp, new Point(0, 0)); } return rotatedImage; }
额外优化建议
你当前的代码存在内存泄漏问题,每次定时器触发都会生成3个新的Bitmap对象,但旧的Bitmap没有被释放,长时间运行会占用大量内存,建议修改timer1_Tick方法:
private void timer1_Tick(object sender, EventArgs e) { if (bmp != null) { // 赋值新图片前先释放旧的图片资源 pictureBox1.Image?.Dispose(); pictureBox1.Image = RotateImage(bmp1, angle); pictureBox3.Image?.Dispose(); pictureBox3.Image = RotateImage(bmp2, rangle); pictureBox2.Image?.Dispose(); pictureBox2.Image = RotateImage(bmp, angle); angle += 10; rangle -= 10; } }
同时可以删除原来写在RotateImage方法里的bmp.MakeTransparent()调用,避免修改原始图片资源。
内容的提问来源于stack exchange,提问作者Jayashanka Anushan
相关产品推荐
相关产品推荐

