Bug? Strange alignment with Canvas.DrawText


Licensed User
Longtime User
I noticed a strange alignment of Canvas.DrawText when &CRLF& is inserted in the text string and "CENTER" is used for alignment. The largest segment of text is centered but the one or two shorter segments are left justified in alignment with the left most character of the centered segment. I don't think CRLF is recognized in B4A Canvas.DrawText, so this is an improvement. I also tested using TextView with carriage returns after each line of text. The carriage returns were recognized in the string variable but the same alignment issue remained. The sample images was generated with .AddImageToAlbum not a screen shot.

Canvas.DrawText("This is"&CRLF&"a test of the"&CRLF&"month", 160, 160, Font.CreateNew(40),
Colors.Black, "CENTER")

Canvas.DrawText("This is a test"&CRLF&"of the"&CRLF&"month", 160, 160, Font.CreateNew(40), Colors.Black, "CENTER")

IMG_0117.JPG IMG_0118.JPG
Note: If I use "LEFT" for alignment, all of the text starts in the middle of the rectangle and goes to the right, the left side of the rectangle is empty. It is not an accidental left alignment.


B4X founder
Staff member
Licensed User
Longtime User
Canvas.DrawText doesn't draw each line separately so it cannot be used to draw multiline centered text.

You can use this code instead:
Sub DrawCenteredText(canvas As Canvas, text As String, Left As Int, Top As Int, Fnt As Font, Color As Int)
   Dim lbl As Label
   lbl.Font =  Fnt
   lbl.TextAlignment = lbl.ALIGNMENT_CENTER
   lbl.TextColor = Color
   lbl.Text = text
   lbl.Multiline = True
   Dim width As Int = text.MeasureWidth(Fnt)
   Dim height As Int = text.MeasureHeight(Fnt) + 50
   lbl.SetLayoutAnimated(0, 1, 0, 0, width, height)
   Dim rect As Rect
   rect.Initialize(Left - width / 2, Top, Left + width / 2, Top + height)
   canvas.DrawView(lbl, rect)
End Sub


Licensed User
Longtime User
Thank you Erel. I will give it a try. I am working on an app that will be in both B4A and B4i. B4i is new to me and I am glad to see it actually has more options with TextView and TextField. I suspect I will have more questions on the B4A side as my chief tester(daughter) said my implementation of TextEdit was not user friendly.