c# - 使用 DrawString 将单个字符居中

标签 c# winforms gdi+ centering drawstring

我已经尝试了所有建议的文本居中方法,但在将单个字符居中时似乎无法获得我想要的结果。

我有一个矩形。在那个矩形中,我用 DrawEllipse 画了一个圆。现在我想使用相同的矩形和 DrawString 在圆圈内绘制一个字符,使其完美居中。

这是我的基本代码:

StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;

using (Graphics g = Graphics.FromImage(xImage))
{
    g.SmoothingMode = SmoothingMode.AntiAlias;
    g.TextRenderingHint = TextRenderingHint.AntiAlias;
    g.CompositingQuality = CompositingQuality.HighQuality;
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.PixelOffsetMode = PixelOffsetMode.HighQuality;

    g.FillEllipse(fillBrush, imageRect.X, imageRect.Y, imageRect.Width - 1, imageRect.Height - 1);

    g.DrawString(Text, font, Brushes.White, imageRect, stringFormat);
}

文本水平居中...但垂直居中不正确。使用像大写“I”这样的对称字符,我发现字符的顶部总是比字符的底部更靠近矩形的边缘。距离可能至少增加了 50%。

我假设它正在为字符测量足够的空间,例如悬卡在较低位置的小写字母“j”。但是,由于我正在尝试创建一个带有单个字母的图形图标,因此我需要更精确的居中。

最佳答案

使用GraphicsPath 完成尺寸计算。

public static void DrawCenteredText(Graphics canvas, Font font, float size, Rectangle bounds, string text)
{
    var path = new GraphicsPath();
    path.AddString(text, font.FontFamily, (int)font.Style, size, new Point(0, 0), StringFormat.GenericTypographic);

    // Determine physical size of the character when rendered
    var area = Rectangle.Round(path.GetBounds());

    // Slide it to be centered in the specified bounds
    var offset = new Point(bounds.Left + (bounds.Width / 2 - area.Width / 2) - area.Left, bounds.Top + (bounds.Height / 2 - area.Height / 2) - area.Top);
    var translate = new Matrix();
    translate.Translate(offset.X, offset.Y);
    path.Transform(translate);

    // Now render it however desired
    canvas.SmoothingMode = SmoothingMode.AntiAlias;
    canvas.FillPath(SystemBrushes.ControlText, path);
}

关于c# - 使用 DrawString 将单个字符居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8435199/

相关文章:

c# - 将数据库嵌入到 C#/VB.net 中的应用程序

c# - DataGridView 双下划线单元格

c++ - 如何释放 Gdiplus::Bitmap::FromFile 分配的内存

c# - 如何正确地将 PrimaryScreen 更改为 AllScreens?

GDI+ 和 WPF 之间的 C# 转换

c# - ReSharper - 使用 Microsoft.Contracts 时可能的空分配

c# - 是否有可能为 const 提供 setter/getter ?

c# - Richtextbox.invoke,C#,窗体仍挂

c# - Pdfium .NET SDK 中的打印功能

c# - 如何在 WinForms 应用程序中测试 Web 浏览器控件的 Web UI?