简体   繁体   English

画一条光滑的弦

[英]Draw a smooth string

I'm trying to create a simple "Avatar" user control in WinForms that draws a string in the middle of the control.我正在尝试在 WinForms 中创建一个简单的“头像”用户控件,该控件在控件中间绘制一个字符串。 However, I can't figure out a way to draw a smooth text.但是,我想不出一种方法来绘制平滑的文本。 Here's the code:这是代码:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
    e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
    e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
    e.Graphics.FillEllipse(_backgroundBrush, 0, 0, Width, Height);

    var fontSize = Width / 3 * 2;
    if(Font.Size != fontSize)
    {
        Font = new Font(_fontFamily, fontSize, _fontStyle, GraphicsUnit.Pixel);
    }

    var stringSize = e.Graphics.MeasureString(_initials, Font);
    var location = new Point((int)((Size.Width - stringSize.Width) / 2),
                             (int)((Size.Height - stringSize.Height) / 2));
    
    e.Graphics.DrawString(_initials, Font, _foregroundBrush, location);
}

I made the font size a little bit bigger to show what I mean.我把字体大小调大一点来表达我的意思。 In the image below, as you can see the M is broken into several parts rather than a smooth line.在下图中,您可以看到 M 被分成几个部分,而不是一条平滑的线。

结果

Update:更新:

Based on the comment from @GyörgyKőszeg, I changed to TextRenderer and it's now looking like it should.根据@GyörgyKőszeg 的评论,我更改为TextRenderer ,现在看起来应该如此。

//e.Graphics.DrawString(_initials, Font, _foregroundBrush, location);
TextRenderer.DrawText(e.Graphics, _initials, Font, location, _foregroundColor);

期望的结果

Converting my comment to an answer upon request:根据要求将我的评论转换为答案:

Use TextRenderingHint.ClearTypeGridFit for the desired result.使用TextRenderingHint.ClearTypeGridFit获得所需的结果。 And if possible use TextRenderer.DrawText instead of Graphics.DrawString whenever possible.如果可能的话,尽可能使用TextRenderer.DrawText而不是Graphics.DrawString TextRenderer.DrawText uses GDI text rendering instead of GDI+ and it is the preferred way of rendering text since .NET Framework 2.0 (even by controls if UseCompatibleTextRendering is false). TextRenderer.DrawText使用 GDI 文本呈现而不是 GDI+,它是自 .NET Framework 2.0 以来呈现文本的首选方式(即使UseCompatibleTextRendering为 false 时也可以通过控件)。

And please also note that you should use TextRenderer.MeasureText instead of Graphics.MeasureString because they may return different sizes.另请注意,您应该使用TextRenderer.MeasureText而不是Graphics.MeasureString ,因为它们可能会返回不同的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM