question

DangDKhanh-2637 avatar image
0 Votes"
DangDKhanh-2637 asked DangDKhanh-2637 commented

Get fontsize base on text width?

Hi,
Suppose I have a CString L"Marks sample" with fixed width = 81(points),
How do I determine its font size?
Assume the font name is Arial and ignore the formatting conditions like bold..

I'm using the GetTextExtentPoint32 function, but it seems to be applying the opposite condition.

Thanks you!.

c++
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Viorel-1 avatar image
0 Votes"
Viorel-1 answered DangDKhanh-2637 commented

If you want to fit the text into some width, then maybe try several font sizes. For example, the next loop starts with 6-point font and increases it until the width is achieved:

 CString text = L"Marks sample";
 CString font_name = L"Arial";
 int required_width_points = 81;
 float font_size_points;
    
    
 CClientDC dc( this );
 dc.SetMapMode( MM_TWIPS );
 int required_width_twips = required_width_points * 20;
    
 for( font_size_points = 6.0;; font_size_points += 0.1 )
 {
    CFont font;
    font.CreatePointFont( font_size_points * 10, font_name, &dc );
    
    CFont* old_font = dc.SelectObject( &font );
    CRect r( 0, 0, 0, 0 );
    dc.DrawText( text, r, DT_LEFT | DT_TOP | DT_SINGLELINE | DT_NOCLIP | DT_NOPREFIX | DT_CALCRECT );
    dc.SelectObject( old_font );
    
    if( r.Width( ) == required_width_twips ) break;
    
    if( r.Width( ) > required_width_twips )
    {
       font_size_points -= 0.1;
       break;
    }
 }

This is the current window (a CWnd*). The result is in font_size_points.

You can also consider a binary search algorithm.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks you for this suggestion,
it's clear to me now!

0 Votes 0 ·
Castorix31 avatar image
0 Votes"
Castorix31 answered DangDKhanh-2637 commented

You can calculate the font size from the height, not the width :

INFO: Calculating The Logical Height and Point Size of a Font


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi,
Thanks you for the link, it gave me a lot of useful information.

0 Votes 0 ·