1

I need to draw a string in a panel perfectly centered, horizontally and vertically.

Centering horizontally is not a big deal using the MeasureString function.

Bug, the MeasureString function returns a height that takes care of every possible char (like P and p), but not the real height of the actual string.

Here is the sample code I'm using :

using (Graphics gr = Graphics.FromImage(mBackImage))
{
    gr.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
    gr.FillRectangle(new SolidBrush(BackColor), new Rectangle(0, 0, this.Width, this.Height));
    var f = new Font(Font.FontFamily, this.ClientSize.Height, FontStyle.Bold, GraphicsUnit.Pixel);
    var sz = gr.MeasureString(Label, f);
    var pt = new PointF((this.ClientSize.Width - sz.Width) / 2, (this.ClientSize.Height - sz.Height) / 2);

    gr.DrawString(Label, f, new SolidBrush(ForeColor), pt);
}

My target is to draw numbers, and the result is that numbers are drawn a little bit too high.

Even if I change the text from "10" to "P", to "p", and I see that the text stays aligned on a "base line".

I really would like to center the text, depending on the real footprint.

How can I achieve this?

Note: this question is absolutely not duplicate of "Center text for receipt printing", because I'm talking about vertical centering, not horizontal centering.

MeasureString or MeasureCharacterRanges are returning sizes taller than the real printed chars, causing vertical alignment issues.

Sierramike
  • 371
  • 4
  • 16
  • [MeasureCharacterRanges()](https://msdn.microsoft.com/en-US/library/system.drawing.graphics.measurecharacterranges(v=vs.110).aspx) might help you. – Nico Schertler May 03 '18 at 06:24
  • Use the Stringformat along with a Rectangle. Much better than any measuring: using (StringFormat fmt = new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }) ` – TaW May 03 '18 at 09:31

0 Answers0