Bitmap与OnPaintBackground中的TextRenderer.DrawText

Jon*_*ury 7 c# textrenderer

如果我使用OnPaintBackground中提供的Graphics对象使用TextRenderer.DrawText(),我的文本看起来很完美.如果我创建自己的Bitmap并使用从我的Bitmap获得的Graphics对象,我的文本看起来很糟糕.看起来它使用黑色对文本进行抗锯齿处理,而不是位图的背景颜色.如果我使用Graphics.DrawString(),我可以避免这个问题,但这种方法有可怕的字距调整问题.我该怎么办?如何使用Bitmap的内容正确地将TextRenderer.DrawText()转换为反别名?

看起来很糟糕:

Bitmap bmp = new Bitmap(100, 100, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.Red);
TextFormatFlags tf = TextFormatFlags.Left;
TextRenderer.DrawText(g, @"C:\Development\Testing\blag", font, clip, Color.White, Color.Transparent, tf);
}
Run Code Online (Sandbox Code Playgroud)

看起来不错,但我想将其渲染到位图上,而不是渲染到控件的表面上:

protected override void OnPaintBackground(PaintEventArgs e)
{
e.Graphics.Clear(Color.Red);
TextFormatFlags tf = TextFormatFlags.Left;
TextRenderer.DrawText(e.Graphics, @"C:\Development\Testing\blag", font, clip, Color.White, Color.Transparent, tf);
}
Run Code Online (Sandbox Code Playgroud)

有什么不同?

Rom*_*kov 9

答案是不要使用TextRenderer.TextRenderer是文本呈现的GDI(非GDI +)实现的包装器,它具有许多功能,但是与您发现的内存DC不能很好地互操作.

使用Graphics.DrawString&Graphics.MeasureString,但请记住将其传递给StringFormat.GenericTypographic以获得准确的大小和位置.

最初引入TextRenderer的原因是GDI +不支持GDI的Uniscribe引擎所做的所有复杂脚本.然而,随着时间的推移,GDI +对复杂脚本的支持已经扩展,现在没有任何充分的理由可以使用TextRenderer(它甚至不再是两者中的更快,事实上它恰好相反).

但实际上,除非您遇到严重的,可衡量的性能问题,否则只需使用Graphics.DrawString.