I have created custom buttons using canvas, and would like to center the text automatically. I’ve put together some code from research that centers it by height perfectly, but am having trouble centering it by width. This is the code for how it centers the text by height just fine.
g.DrawString("Test", g.StringWidth("Test"), g.Height-g.TextHeight /2)
However, when I attempt to add any code that logically (at least to me anyway) adds centering of the text by width, it doesn’t work. I’m sure it’s something super simple I’m missing.
Greg_O
(Greg O)
May 19, 2023, 8:06pm
2
Var x as double = (g.width - g.stringwidth("test")) / 2
You need to compute where to start drawing the text using g.TextWidth.
That resulted in no text showing up.
I tried using g.TextWidth in various ways. No luck.
Here’s how I centre text in a control that I use as a title area in a DesktopContainer
xVal = 0.5 * (me.Width - g.TextWidth (titleText))
yVal = if (titleYValue=0, (0.5 * (me.Height - g.FontSize)) + 12, titleYValue)
g.DrawText (titleText, xVal, yVal)
Ignore the yVal part.
If I ignore the yVal part, I get an error because drawstring is expecting 3 arguments
dim xVal as integer
xVal = 0.5 * (me.Width - g.TextWidth ("Test"))
g.DrawText ("Test", xVal)
I meant you supply your own yVal, ignore my bit of code for that. But add:
Var xVal, yVal As Double
TimStreater:
Var xVal, yVal As Double
Var xVal, yVal As Double
xVal = 0.5 * (me.Width - g.TextWidth ("Test"))
yVal = 0.5 * (me.Height - g.TextHeight ("Test"))
g.DrawText ("Test", xVal, yVal)
Doesn’t work. Xojo complains about more than one method with this name.
Look up the doc for graphics and then see the TextHeight method.
Yeah, I already read that. If I found it helpful, I wouldn’t bet in here.
You didn’t notice that of the two method signatures offered, one requires no arguments and the other requires two?
Got it.
Var xVal, yVal As Double
xVal = 0.5 * (g.Width - g.TextWidth ("Test"))
yVal = 0.5 * (g.height - g.TextHeight) + g.TextAscent
g.DrawText ("Test", xVal, yVal)
MarkusR
(MarkusR)
May 20, 2023, 4:32am
14