Forum Archive

measure_string replacement

mikael

These days I am getting unsatisfactory results from ui.measure_string, probably because it is based on a deprecated method.

Would anyone have already cooked up an ObjC replacement?

cvp

@mikael compare

import ui
l = ui.Label()
l.border_width = 1
l.text = 'test'
l.present()
l.size_to_fit()
print(l.width)
print(ui.measure_string(l.text,font=l.font)[0])

You could use this feature with hidden label, even without present, here only to see the width

cvp

@mikael no more time today but I just remember this little script that will allow you to find an Objective C way

import ui
from objc_util import *
tv = ui.TextView()
tv.font = ('<System-Bold>',32)
tv.text = 'this is a sample but could be longer'
tv.frame = (0,0,200,200)
tv.present('sheet')
tvo = ObjCInstance(tv)
#print(dir(tvo))
txt = 'ampl'
i = tv.text.find(txt)
p1 = tvo.positionFromPosition_offset_(tvo.beginningOfDocument(), i)
p2 = tvo.positionFromPosition_offset_(tvo.beginningOfDocument(), i+len(txt))
rge = tvo.textRangeFromPosition_toPosition_(p1,p2)
rect = tvo.firstRectForRange_(rge)  # CGRect
x,y = rect.origin.x,rect.origin.y
w,h = rect.size.width,rect.size.height
print(x,y,w,h)
l = ui.Button()
l.frame = (x,y,w,h)
l.background_color = (1,0,0,0.5)
l.corner_radius = 10
l.border_width = 1
def button_action(sender):
    if l.background_color == (1,0,0,0.5):
        sender.background_color = (0,0,1,0.5)
    else:
        sender.background_color = (1,0,0,0.5)
l.action = button_action
tv.add_subview(l)

mikael

@cvp, yes, do not know why, but for me measure_string started missing the correct height, with a fixed width, exactly by one line, regardless of the amount of text.

For me, the solution with a ui.Label was to use:

sz = label.objc_instance.sizeThatFits_(objc_util.CGSize(label.width, 0))