g.DrawText, centered

How to center a text on a canvas?

or how to know the wide of a string, (knowing FontSize, and g.FontName)?

g.DrawText(aReceivedText, x, y)

First set the properties of the Graphics context:

g.FontName = "FontName" g.FontSize = 14 g.Bold = True

Then calculate the dimensions of your string:

dim dblWidth as Double = g.TextWidth( "My String" ) dim dblHeight as Double = g.TextHeight( "My String", dblW )

Next get your calculated X and Y positions:

dim dblX as Double = (g.Width / 2) - (dblWidth / 2) dim dblY as Double = (g.Height / 2) - (dblHeight / 2) + g.TextAscent

Finally, draw your string:

g.DrawText( "My String", dblX, dblY, dblWidth )
2 Likes

see also Graphics/Multimedia Vector Graphics
documentation.xojo.com/api/graphics/textshape.html (old StringShape)
it have a Alignment

1 Like

[quote=461445:@Markus Rauch]see also Graphics/Multimedia Vector Graphics
documentation.xojo.com/api/graphics/textshape.html (old StringShape)
it have a Alignment[/quote]
Thanks, I’ll try it also.

or save a few nanoseconds… divide is an expensive operation

dim dblX as Double = (g.Width-dblWidth) / 2
dim dblY as Double = ((g.Height-dblHeight) / 2) + g.TextAscent
1 Like

Or show them how to do it the long way so that they have a better understanding of the operation they need help with at a glance. :wink:

1 Like

and with this posting… they now know both ways