how to make text to adapt to its control

I’m trying to find a way to make a certain text adapt to its control, in this case it’s a button (win.butt)
With the method below, given a string I want to find what is the maximum textsize possible to stay within 80% of the width of
the button controls that Im using.
I know that graphicsstringwidht uses pixels so I changed the units of the button fonts in pixels but still is not working.

Any clues pls, thanks


idealtextsize(word as string) as integer

  Dim p as new picture (20,22,32)
  p.Graphics.textfont=win.butt(1).textfont
  p.Graphics.TextSize=win.butt(1).textsize
  p.graphics.textunit=fontunits.Pixel
  win.butt(1).TextUnit=fontunits.pixel
  p.graphics.textsize=1

do
    p.graphics.textsize=p.graphics.textsize+5
    win.title=str(p.graphics.textsize)
  loop until p.graphics.stringwidth(word)>=80*win.butt(1).width
  
  return p.graphics.textsize

the method is slow and almost freezes and the captions “disappear”

what I do outside the method is this

button.textize=idealtextsize(word) ’ word is the caption for the button control

  1. create a graphics object [dim g as graphics=p.graphics] and use it [ie. create one reference one time]
  2. do not keep assigning win.title inside the loop… it is doing nothing productive
  3. precalculate 0.80*win.butt(1).width [fyi… it looks like you have 80.0]
  4. convert it from a loop to a binary search… you will hit the right value in a few attempts [I will leave this as an educational]
  5. start at a value other than 1. You can probably guess a better starting value than that

could it be that graphicsstringwidth returns a value in pixels while controls.width is in points ?

Why nobody gives two quacking ducks about autolayout in xojo ?

auto-layout may be available in a future version of Xojo… but that doesn’t solve your problem today

Since the pixels in pictures are the same size as point, it is one and the same thing.

Autolayout will not solve what you are trying to do. It manages the dimension of controls, not that of the text you put inside.