使用DrawString将单个角色居中

时间:2011-12-08 17:39:28

标签: 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"哪个挂得更低。但是,由于我试图用单个字母创建一个图形图标,我想要更精确的居中。

3 个答案:

答案 0 :(得分:7)

使用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);
}

答案 1 :(得分:0)

如果您使用

StringFormat stringFormat = new StringFormat(StringFormat.GenericTypographic);
你有

enter image description here

代替

enter image description here

希望这会有所帮助

答案 2 :(得分:0)

虽然John Arlen的答案很完美,但我想发表我的回答:

    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));
    }

代码结果如下: result in my computer

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

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


|顶部填充1/6

|字体3/6

| word descender 1/6

|底部填充1/6