Get fontsize base on text width?

DangDKhanh-2637 946 Reputation points
2021-07-24T02:32:11.507+00:00

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++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,720 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 117.2K Reputation points
    2021-07-24T08:38:20.337+00:00

    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 additional answer

Sort by: Most helpful
  1. Castorix31 85,126 Reputation points
    2021-07-24T06:02:59.667+00:00

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

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


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.