0

From this post, Let's say I want to calculate the textwidth in point of "Meet".

I use the following code:

    HFONT hFont, hOldFont;
    double fontheight = 12; <--font height in point
    HDC hDC = GetDC(0);
    // get a 12-point font and select it into the DC
    int currentY = MulDiv((int)fontheight, GetDeviceCaps(hDC, LOGPIXELSY), 72);
    
    hFont = CreateFont(-currentY, 0, 0, 0,  FW_NORMAL, 0, 0, 0, 0,
        0, 0, 0, 0, L"Arial"));
    hOldFont = SelectFont(hDC, hFont);
    TEXTMETRIC textMetric;
    GetTextMetrics(hDC, &textMetric);  <--this function return char height=18/charwidth=7
    double fontwidth = fontheight/textMetric.tmHeight* textMetric.tmAveCharWidth; //rescale font width base on font height
    CString t = L"Meet";
    fontwidth =(double) (fontwidth* t.GetLength()); <-fontwidth*4.

Where am I going wrong, because based on the actual image it is quite small?

Yen Dang
  • 268
  • 2
  • 9
  • 1
    `12/18` is an *integer division* and will result in zero. You may want `12.0/18` instead. – MikeCAT Jul 22 '21 at 10:55
  • Hi @MikeCAT, Thanks for pointing that out, in fact I use this code: `fontheight/textMetric.tmHeight* textMetric.tmAveCharWidth` . I have abbreviated so you can see if my calculation is right or wrong. – Yen Dang Jul 22 '21 at 10:58
  • Well that "abbreviation" turns out to give wrong results. Remember to always post a [mcve] that replicates the error you have and don't contain any other errors (which can mislead us). Is the actual error this integer division "abbreviation", or something else? Of something else, then please post the actual code you use. – Some programmer dude Jul 22 '21 at 11:01
  • Hi @Someprogrammerdude, Thanks you. I made the calculation more clear but in fact, I definitely won't write like that because the font height can always change. The post has been updated – Yen Dang Jul 22 '21 at 11:04
  • 1
    Hi, Thanks all. I missed GetTextExtentPoint32 function. my problem has been resolved. – Yen Dang Jul 22 '21 at 12:19
  • @YenDang If you think the solution could be useful for others, then please post an actual answer ([read about how to write good answers](https://stackoverflow.com/help/how-to-answer)). – Some programmer dude Jul 22 '21 at 12:40

0 Answers0