Canvas DrawString Text Position (Justification)

I am trying to draw the numbers around the ticks of a 12 hour clock.
I can draw the ticks quite simply with r sin/cos from the center a canvas.
However when trying to put number beside each tick I have a small problem.
The text is positioned too far right at 3 O’clock, but are too far left at 9 O’clock.
There is a similar issue with the text at 12 O’clock and 6 O’clock. Too high at the top ‘and’ bottom.

This in my opinion is because the text position of the text is the bottom left of the character.

I need my text position to be the center of that text character(s).

Justification of the text fix this but I can’t seem to find a property for text justification in graphics or the canvas.

I might be able to fix this simply “IF” I knew how to get the size of the ‘rendered’ text in pixels.

g.TextUnit = FontUnits.Point
g.TextSize = 16

72 Points / Pixel?

And TextWidth/TextHeight don’t do the job? I know these deliver Points, but… :slight_smile:

You can measure the width of the string and divide by 2 to calculate the horizontal centre.

Unfortunately, there is no function to calculate the exact height of a string of characters. There are functions available (TextHeight / TextAscent etc…) but they don’t take into account the actual characters in the string. If you want a really accurate height you would have to draw the text into a picture and find the bounding box by testing the pixel values.

I have to do this for a specific project.
If you have MBS plugins, you can use the GMImage

 p =  new  picture (100,100,32) = &c000000 = "Arial" = 64 "G",0,62
    gm = new GMImageMBS(p)
 //then examine gm.boundingbox  properties such as 
    //  gm.boundingBox.xOff 
  // gm.boundingBox.width
 // gm.boundingBox.yOff
1 Like

I posted code that I use for vertically and horizontally centering text a couple of years ago. Should be trivial to modify it to suit your needs. Be sure to read all the way down for an improved Y positioning calculation.

1 Like

have you test TextShape?

1 Like