通过Graphics类可以给图片上添加文字,有很多教程提供了相关指导,例如C#指定图片添加文字。
但如何修改并选择文字的渲染效果参数的指导文章比较少见,官网资料也多是文字描述,缺少完整的各个选项效果demo。这里我结合微软官网的资料和自己制作的demo图片,实践学习了一下各个渲染效果的表现。
不同渲染效果
实际的文字图像化后,有多种渲染效果:
系统默认的渲染效果,基于RGB结构的渲染,向左右像素借用临近子像素做抗锯齿平滑渲染,边缘是偏红或偏蓝的,如图1:
但更多情况,更多平台和系统采用基于灰度的抗锯齿渲染,边缘是不同灰度的,如图2:
而不是我们理解的非黑即白的文字,如图3:
其他各个条件的demo code的输出图见附件:
Demo Code
demo code遍历了 *TextRenderingHint*属性的每一个 *TextRenderingHint* 枚举,和3个不同等级的*TextContrast* 值来体现效果。
已知建立了一个 Bitmap 类的 bmpFile文件,在其基础上绘图
//初始化注释文字格式
Graphics g = System.Drawing.Graphics.FromImage(bmpFile);
//初始化字体
Font myFont = new Font(FontFamily.GenericSansSerif, 20,FontStyle.Regular);
//Index 0
//设置文字渲染模式
g.TextRenderingHint =System.Drawing.Text.TextRenderingHint.SystemDefault;
//在图上书绘制文字
// Draw the string.
g.DrawString("This is: SystemDefault", myFont, Brushes.White, 20.0F, 20.0F);
//Index 1
//设置文字渲染模式
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
//在图上书绘制文字
// Draw the string.
g.DrawString("This is: SingleBitPerPixelGridFit", myFont, Brushes.White, 20.0F, 60.0F);
//Index 2
//设置文字渲染模式
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
//在图上书绘制文字
// Draw the string.
g.DrawString("This is: SingleBitPerPixel", myFont, Brushes.White, 20.0F, 100.0F);
//Index 3
//设置文字渲染模式
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
//在图上书绘制文字
// Draw the string.
g.DrawString("This is: ClearTypeGridFit", myFont, Brushes.White, 20.0F, 140.0F);
//Index 4
//设置文字渲染模式
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
//在图上书绘制文字
// Draw the string.
g.DrawString("This is: AntiAliasGridFit", myFont, Brushes.White, 20.0F, 180.0F);
//Index 4
//设置文字渲染模式
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
//在图上书绘制文字
// Draw the string.
g.DrawString("This is: AntiAlias", myFont, Brushes.White, 20.0F, 220.0F);
// Set the text contrast to a high-contrast setting.
g.TextContrast = 0;
//在图上书绘制文字
// Draw the string.
g.DrawString("TextContrast=0", myFont, Brushes.White, 20.0F, 260.0F);
// Set the text contrast to a mid-contrast setting.
g.TextContrast = 6;
//在图上书绘制文字
// Draw the string.
g.DrawString("TextContrast=6", myFont, Brushes.White, 20.0F, 300.0F);
// Set the text contrast to a high-contrast setting. gamma矫正数值在0~12之间
g.TextContrast = 12;
//在图上书绘制文字
// Draw the string.
g.DrawString("TextContrast=12", myFont, Brushes.White, 20.0F, 340.0F);
g.Dispose();
myFont.Dispose();
最终输出:
(需要另存为本地看,bmp文件,网页端浏览被压缩)