1.

Can I Find Out How Long (wide) A String Is In A Certain Font?

Answer»

In PyGTK2, you can use pango CALLS to find out how wide a string will be, using the pango context of the widget that contains (or that will contain) your text:

context = widget.get_pango_context()
metrics = context.get_metrics('font name, 12')
width = pango.PIXELS(metrics.get_approximate_char_width() * n_chars)

For a monospaced font, this should be quite ACCURATE. You can then use widget.set_size_request() if you would like to set that width as the minimum width for the widget/view.

In PyGTK-0.6, you can ask the font directly how long a given string is going to be, as well as how high. Retrieve the font object from the style, and then query it with the string in question:

font = widget.get_style().font

h = font.height(my_string)
w = font.width(my_string)

The methods return pixel counts. You can then set the size manually to any function of those parameters. For instance, to make a widget twice as wide and as high as the string you MEASURED with, use:

widget.set_usize(w*2, h*2)

In PyGTK2, you can use pango calls to find out how wide a string will be, using the pango context of the widget that contains (or that will contain) your text:

context = widget.get_pango_context()
metrics = context.get_metrics('font name, 12')
width = pango.PIXELS(metrics.get_approximate_char_width() * n_chars)

For a monospaced font, this should be quite accurate. You can then use widget.set_size_request() if you would like to set that width as the minimum width for the widget/view.

In PyGTK-0.6, you can ask the font directly how long a given string is going to be, as well as how high. Retrieve the font object from the style, and then query it with the string in question:

font = widget.get_style().font

h = font.height(my_string)
w = font.width(my_string)

The methods return pixel counts. You can then set the size manually to any function of those parameters. For instance, to make a widget twice as wide and as high as the string you measured with, use:

widget.set_usize(w*2, h*2)



Discussion

No Comment Found