Get width of Graphics::drawSingleLineText?


#1

I was looking at the graphics class and there doesn't seem to be a means to get the width of a single text line, esp. if you change the size of the font. 

i.e. 

g.setFont( new Font("Times New Roman" );
g.setFont( 36.f );
g.drawSingleLineText( "Hello TimesNewRoman", 30, 30 );

The problem i've found is that getStringWidth(" Hello TimesNewRoman") gets the width as tho the font is set to the initial size when loading in a new font, which I guess is 14.   it doesn't take into account the setFont( 36.f ).   

the workaround I found is: 

float fontScale = newFontHeight / font.getHeight();
float actualStringWidth = font.getStringWidth(String) * fontScale; 

#2

Just call getStringWidth on a Font object with the size you actually want!


#3

I'm not following.  can you explain how to do that when the font is created with a TypeFace::Ptr ? 


#4

Font f ("times new roman");

f.setHeight (36.0f);

f.getStringWidth()


#5
    Font theFont ("Times New Roman", "Regular", 36.0f);

    g.setFont (theFont);
    
    String szText ("Hello TimesNewRoman");
    
    int textWidth = g.getCurrentFont().getStringWidth (szText);
    int textHeight = g.getCurrentFont().getHeight();
    
    g.drawRect (10, 60, textWidth, textHeight);
    
    g.drawText (szText, 10, 60, textWidth, textHeight, Justification::centredLeft, false);

Rail


#6

i did that with my embedded ttf file (inside BinaryData).  it looks like the font itself has a bunch of white space around each character.  that's what was causing me problems, as the results didn't look right whenever I tried to place stuff relative to a g.drawSingleLineText()'s position.   Thanks for clarifying!