『备注』GDI+ 绘制文本有锯齿,透明背景文本绘制
背景:
GDI+ 绘制文本 时,如果 背景是透明的 —— 则会出现 锯齿。
1 //其实,我不用这三个 属性 好多年了 2 //而且,这三个属性 在关键时刻还有可能 帮倒忙 3 //关键是:这三个属性,鸟用都没有 —— 不能消除锯齿 4 g.SmoothingMode = SmoothingMode.HighQuality; 5 g.InterpolationMode = InterpolationMode.HighQualityBicubic; 6 g.CompositingQuality = CompositingQuality.HighQuality;
解法:
1 Bitmap bitmap0 = new Bitmap(400, 200); 2 using (Graphics g = Graphics.FromImage(bitmap0)) 3 { 4 g.Clear(Color.Transparent); //以透明色 作为背景 5 g.DrawString("科技救国 (透明色背景)", new Font("微软雅黑", 14), new SolidBrush(Color.Black), new PointF(10, 10)); 6 bitmap0.Save(@"D:\XXX\TestString0.png", ImageFormat.Png); 7 } 8 9 10 11 Bitmap bitmap1 = new Bitmap(400, 200); 12 using (Graphics g = Graphics.FromImage(bitmap1)) 13 { 14 g.Clear(Color.White); 15 g.DrawString("科技救国 (白色背景)", new Font("微软雅黑", 14), new SolidBrush(Color.Black), new PointF(10, 10)); 16 bitmap1.Save(@"D:\XXX\TestString1.png", ImageFormat.Png); 17 } 18 19 20 Bitmap bitmap2 = new Bitmap(bitmap1.Width, bitmap1.Height); 21 for (int x = 0; x < bitmap1.Width; x++) 22 for (int y = 0; y < bitmap1.Height; y++) 23 { 24 //这段代码还有很大的优化空间 25 Color color = bitmap1.GetPixel(x, y); 26 byte a = (byte)(((short)(255 - color.R) + (short)(255 - color.G) + (short)(255 - color.B)) / 3); 27 Color color2 = Color.FromArgb(a, 0, 0, 0); 28 bitmap2.SetPixel(x, y, color2); 29 } 30 31 bitmap2.Save(@"D:\XXX\TestString2.png", ImageFormat.Png);
结果: