Reputation: 546
What I'm attempting to do is draw a number inside a circle so that it's positioned centrally both vertically and horizontally. I'm drawing both the circle and text string using the same rectangle structure and using center for both horizontal and vertical alignments. But, as you can see from the image where I drew a horizontal line across the white circle, the text is aligning its base line centrally and my eye says it's horizontally aligning slightly to the left.
I've tried fudging by adding string.height/2 to the top of the rectangle to shift it down 1/2 its height but it's still not correct. (I adjust the font size so the number will fit within the box according to the number of digits in the counter)
How can I do this properly please?
var rect = new Rectangle(bmpWidth - maxCircleDiameter, bmpHeight - maxCircleDiameter, maxCircleDiameter, maxCircleDiameter);
g.FillEllipse(Brushes.White, rect);
using (var format = NewClassFactory.GetFormat(StringAlignment.Center, StringAlignment.Center, StringTrimming.Character))
g.DrawString(toDisplay, newFont, Brushes.Black, rect, format);
Upvotes: 2
Views: 1336
Reputation: 125197
You can use TextRenderer.DrawText
to draw a text in a rectangle bound, using a color and font and specifying different text format flag:
var rect = new Rectangle(10, 10, 32, 32);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.FillEllipse(Brushes.White, rect);
TextRenderer.DrawText(e.Graphics, "100", this.Font, rect, Color.Black,
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
Upvotes: 2