2

I have an application which at some point draws many circles on a Panel control. Then I want to name each circle (just a letter and a number). And I want the text to be centered, to make it look nice. For now, I have something like this:

enter image description here

What I do, is I take the center of that circle, and do the following:

Graphics.DrawString($"s{i+1}", panel.Font, new SolidBrush(Color.White), pointOnCircle.X, pointOnCircle.Y);

(the pointOnCircle.X and Y being the coordinates of the center). And as you can see, it looks kinda bad.

My question here would be: Is there a way to somehow calculate that X and Y for a specified font size and those small circles radius, to make it look centered?

The result from using the accepted answer or @Johnny Mopp comment:

enter image description here

minecraftplayer1234
  • 2,127
  • 4
  • 27
  • 57
  • 1
    [How to: Align Drawn Text](https://learn.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-align-drawn-text) – 001 Oct 10 '18 at 17:05
  • 1
    Do __not__ measure or calculate anything. The __system__ will do a better job: Simply use [centered stringformat](https://stackoverflow.com/questions/32880669/how-many-spaces-does-t-use-in-c-sharp/32892371#32892371) and draw into the very same rectangle you used for the ellipse. – TaW Oct 10 '18 at 17:06
  • @JohnnyMopp, you should put that as an answer, not a comment! Great advice, did the job 100%! Edited the question with the result – minecraftplayer1234 Oct 10 '18 at 17:13

2 Answers2

3

You need to use an overload of the DrawString method that takes a StringFormat argument and then use the StringFormat.Alignment and StringFormat.LineAlignment to align the string in the center and the middle of the circle:

using (StringFormat sf = new StringFormat())
{
    sf.Alignment = StringAlignment.Center;
    sf.LineAlignment = StringAlignment.Center;

    Graphics.DrawString($"s{i + 1}", panel.Font, new SolidBrush(Color.White),
                        pointOnCircle.X, pointOnCircle.Y, sf);
}
1

Use Graphics.MeasureString to get the size (X and Y) of a string for a specified font. You can use the resulting size to center your text.

MikeH
  • 4,242
  • 1
  • 17
  • 32