I am trying to use ui.measure_string. I do a simple call to print out the results. I get a tuple (0,0) as the result. It seems weird as I am not doing anything tricky. The documentation says it will return the width,height as it would be rendered with draw_string, given the optional parameters of font etc. My plan is to use it with labels, I assume the labels are also rendered with draw_string.
The simplest code possible below returns (0.0, 0.0)
import ui print ui.measure_string('my name')
Any help appreciated
dgelessus last edited by
I think you need to call that function from within a
GState. Never used those, so I can't help you very much, but they're documented near the bottom of the
ccc last edited by
The code above give me
(50.88, 14.32)but I am running today's Beta release.
omz last edited by
ui.measure_stringis mostly broken in 1.5.
Ok, thanks omz. Not a huge problem.
This appears to work. I have done some tests. Appears to be 1 or 2 pixelsout. But this could be margins in the label. Anyway, close enough for what I wanted. Maybe there's a lot easier way to do this. It's the best I could come up with my limited experience. I did it as a class so not to have the overhead of setting up the image etc... If this is a stupid idea or there is a far simpler way of doing it , would appreciate the feedback.
import Image, ImageDraw, ImageFont class MeasureString(object): def __init__(self, font): self.image = Image.open("") self.draw = ImageDraw.Draw(self.image) self.font = ImageFont.truetype(font, font) def set_font(self, font): #not sure if i have to del the prev font self.font = ImageFont.truetype(font, font) def measure_string(self, s, font = None): self.set_font(font) if font else False return self.draw.textsize(s, self.font) def __del__(self): # i think this is correct del self.draw if __name__ == '__main__': font = ('Helvetica', 16) ms = MeasureString(font) print ms.measure_string('a test string')
Hmmmm, well I feel pretty stupid now. As useless as the above code is, still helped me learn something.
I guess the more correct code should be
import ImageFont def measure_string(s, font): return ImageFont.truetype(font, font).getsize(s) f = ('Helvetica', 16) print measure_string('i made a foolish mistake', f)
Live an learn :)