6

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

我有一个矩形。在那个矩形中,我用 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”这样挂得更低的字符测量足够的空间。但是,由于我正在尝试使用单个字母创建图形图标,因此我想要更精确的居中。

4

3 回答 3

9

用于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);
}
于 2011-12-08T19:26:22.543 回答
1

如果你使用

StringFormat stringFormat = new StringFormat(StringFormat.GenericTypographic);

你得到了

在此处输入图像描述

反而

在此处输入图像描述

希望这可以帮助

于 2011-12-08T17:59:49.920 回答
0

虽然约翰·阿伦的回答很完美,但我想发表我的回答:

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
         // Set up string.
        string measureString = "HelloWorld";
        Font stringFont = new Font("Arial", 100, FontStyle.Regular, GraphicsUnit.Pixel);

        // Measure string.
        SizeF stringSize = new SizeF();
        stringSize = e.Graphics.MeasureString(measureString, stringFont);

        // Draw rectangle representing size of string.
        e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 10.0F, 10.0F, stringSize.Width, stringSize.Height);

        // Draw string to screen.
        e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(10, 10f + stringSize.Height / 12.0f));
    }

代码结果是这样的: 导致我的电脑

“HelloWorld”在红色框中垂直居中。

因为下降线的高度大约等于 1/6stringSize.Height计算的MeasureString


| 顶部填充 1/6

| 词体 3/6

| 字下降 1/6

| 底部填充 1/6

于 2014-03-06T12:12:40.040 回答