Android Question [Solved] Finding Character Width with B4XCanvas

Roger Daley

Well-Known Member
Licensed User
Longtime User
Hi All,

I am trying to find a Chr.width with B4XCanvas in order to set the text size of an edittext correctly. [nothing new.]

With Canvas this is basically the code I have used in the past.
B4X:
Private Canvas1 As Canvas

Canvas1.Initialize(Activity)
fontsize as Float  = 26
chrwidth as Float
chrwidth = Canvas1.MeasureStringWidth("9", Typeface.DEFAULT, fontsize)

... and then through a loop adjust the font size to match the edittext.

In B4XPages using B4XCanvas I don't have a "FontSize" parameter. In searching a few examples what is done in respect of FontSize escapes me.

B4X:
Private Canvas1 As B4XCanvas
Private ChrRect  As B4XRect
fontsize as Float  = 26
chrwidth as Float
Canvas1.Resize(Panel1.width, Panel1.height)
ChrRect = B4XCanvas1.MeasureText("9", Typeface.DEFAULT)
ChrWidth = ChrRect.Width

Somewhere the size of the font is included, any hints would be great.

Regards Roger
 

Roger Daley

Well-Known Member
Licensed User
Longtime User
Thanks Klaus,

I was just typing that I had solved my issue by creating a B4X font, which includes the font size when your post came through. Your expression is far more elegant than mine.:)

B4X:
Private Canvas1 As B4XCanvas
Private ChrRect  As B4XRect
Private Xfont As B4XFont = xui.CreateDefaultFont(fontsize)
fontsize as Float  = 26
chrwidth as Float
Canvas1.Resize(Panel1.width, Panel1.height)
ChrRect = B4XCanvas1.MeasureText("9", Xfont)
ChrWidth = ChrRect.Width

Many Thanks Klaus
 
Upvote 0
Top