WebCanvas Text Alignment
Posted by Greg O'Lone
Why doesn't the WebGraphics class have a StringWidth method?
Dim txt as String = "Hello World" Dim y as Integer = 100 Dim AlignX as Integer = g.Width/2 Dim w as Integer = g.StringWidth(txt) Dim x as Integer = (AlignX-w)/2 g.DrawString txt,x,y
If you were trying to do this with a WebCanvas, the problem is the call to g.StringWidth. That would need to call out to the browser to get the result because that's where the physical canvas and the HTML5 rendering engine actually is. Since calls to/from the browser are asynchronous, you wouldn't be able to get the result back until some time in the future, long after your drawing code has run.
The solution we provided is a rather simple one. Why not tell the canvas what type of alignment you want...
Dim txt as String = "Hello World"
Dim y as Integer = 100 Dim AlignX as Integer = g.Width/2 g.TextAlignment = WebGraphics.TextAlignmentCenter g.DrawString txt,AlignX,y
The Xojo Framework does the math for you right on the browser! The TextAlignment property supports Left, Center and Right alignment so you don't need to know the width of the string to calculate alignment any more.
Want to do Decimal alignment? Convert the currency to a string and split it into the text that needs to draw on the left and the text that needs to draw on the right of the decimal point, and draw it in two pieces, like this:
Dim c as currency = 15.32
dim parts() as String = Split(Str(c,"0.00"),".") Dim y as Integer = 100 Dim AlignX as Integer = g.Width/2 g.TextAlignment = WebGraphics.TextAlignmentRight g.DrawString Parts(0)+".", AlignX, y
g.TextAlignment = WebGraphics.TextAlignmentLeft
g.DrawString Parts(1), AlignX, y
As you can see, the TextAlignment property gives you a lot of flexibility without needing to know the actual width of the string you are drawing.