为什么这段代码不能将文本居中放在图形对象上?

时间:2014-02-26 02:35:52

标签: c# winforms .net-4.5

我使用图形对象方法MeasureCharacterRanges()时遇到了麻烦。下面是不起作用的示例代码。绘制矩形时,它不在'X'周围,而是在左侧

显然,'X'并不标志着这一点。

为什么?

public partial class Form1 : Form
{
    private string test = "X";

    public Form1()
    {
        InitializeComponent();
        this.ResizeRedraw = true;
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        using (Graphics g = this.CreateGraphics())
        {
            g.Clear(this.BackColor);
            using (Font font = new Font(Font.Name, this.Size.Height / 8))
            {
                Rectangle layout = this.ClientRectangle;
                layout.Width *= 2;

                using (StringFormat stringFormat = new StringFormat())
                {
                    CharacterRange[] charRange = { new CharacterRange(0, test.Length) };
                    stringFormat.SetMeasurableCharacterRanges(charRange);
                    Region[] sr = g.MeasureCharacterRanges(test, font, layout, stringFormat);

                    RectangleF rectangle = sr[0].GetBounds(g);

                    PointF location = new PointF((this.ClientRectangle.Width - rectangle.Width) / 2.0f, ((this.ClientRectangle.Height - rectangle.Height) / 2.0F));
                    rectangle.Location = location;
                    using (SolidBrush brush = new SolidBrush(Color.Black))
                    {
                        g.DrawString(test, font, brush, rectangle.Location);
                    }
                    g.DrawRectangle(Pens.Red, Rectangle.Round(rectangle));
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您需要使用GenericTypographic属性创建StringFormat,然后使用其他一个重载将stringFormat传递给DrawString方法,以便它知道您指定的StringFormat。

如果不这样做,DrawString只使用默认的StringFormat,它没有Trimming,FormatFlags和Alignment等正确的Property值。

    // StringFormat created using GenericTypographic
    using (StringFormat stringFormat = new StringFormat(StringFormat.GenericTypographic))
    {
        CharacterRange[] charRange = { new CharacterRange(0, test.Length) };
        stringFormat.SetMeasurableCharacterRanges(charRange);
        Region[] sr = g.MeasureCharacterRanges(test, font, layout, stringFormat);

        RectangleF rectangle = sr[0].GetBounds(g);

        PointF location = new PointF((this.ClientRectangle.Width - rectangle.Width) / 2.0f, ((this.ClientRectangle.Height - rectangle.Height) / 2.0F));
        rectangle.Location = location;

        using (SolidBrush brush = new SolidBrush(Color.Black))
        {
            // Now passing in stringFormat
            g.DrawString(test, font, brush, rectangle.Location, stringFormat);
        }
        g.DrawRectangle(Pens.Red, Rectangle.Round(rectangle));

    }