[haiku-3rdparty-dev] Re: Know size of DrawString?

  • From: Stephan Aßmus <superstippi@xxxxxx>
  • To: haiku-3rdparty-dev@xxxxxxxxxxxxx
  • Date: Tue, 15 Nov 2011 14:36:52 +0100

On 15.11.2011 14:07, Rene Gollent wrote:
On Tue, Nov 15, 2011 at 7:45 AM, hey68 you<hey68you@xxxxxxxxx>  wrote:
The string contents will change and I need to adjust the size of the BView
based on the new string size.

You want StringWidth(text) . It returns a float giving you the width
of the string
in the current font.

Yes, but you will also want the font_height. You can either get the current BFont of the BView by calling...

BFont font;
GetFont(&font);

font_height fontHeight;
font.GetHeight(&fontHeight);

...and then use the font to do other stuff as well. Or maybe you just configured the BFont on the BView and still have the BFont object around. Otherwise you can use the shortcut BView method:

font_height fontHeight;
GetFontHeight(&fontHeight);

And then the required height of the string is ceilf(fontHeight.ascent) + ceilf(fontHeight.descent) + any border margins you want added (which should be based on the font height for aesthetical reasons).

While we're at it, what about a way to center-align the drawn string within
the BView?

That's quite easy though, given the above width calculation:
float stringWidth = StringWidth(yourtext);
DrawString(yourtext, BPoint((Bounds().Width() - stringWidth) / 2.0, 5.0));

What is "5.0"? This won't work. The vertical coordinate passed to DrawString is the baseline position. This is explained in more detail in the BView chapter on drawing and/or DrawString. In a nutshell, the baseline offset is the fontHeight.ascent from the top of the string bounds. So to center text vertically you have to use this calculation:

float stringHeight = ceilf(fontHeight.ascent) + ceilf(fontHeight.descent);

float baseline = (Bounds().Height() - stringHeight) / 2 + floorf(fontHeight.ascent + 0.5);

Best regards,
-Stephan

Other related posts: