开发者

How to get the automatically calculated font width from a CFont Object?

I'm using a fixed size font ( eg: "Courier New" ). When I initialize the CFont object by calling CFont::CreateFont function, I want to specify only the font height.

CFont Font;
Font.CreateFont( nFontHeight, 0, 0, 0, 0, false, false,
    0, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
    FIXED_PITCH|FF_MODERN, _T("Courier New") );

As per documentation, font width will be calculated automatically. I need that a开发者_运维问答utomatically calculated value for some other calculation.

GetLogFont Function is useless as it seems CFont only holds the value we give that is width = 0 and it calculates the value only when it is used for first time. ( Please check the Microsoft documentation )

Another option was to use CDC::GetTextExtent using a single character. But in that case also I could see some minor differences even in the height. For example, when I give -32 as height, GetTextExtent returns 33 for y value.

Is there any way to get the correct calculated width?


First of all, if you only want to specify the font height, you normally want to use CreatePointFont. Second, Windows 95/98/SE/Me are dead and gone -- and with them, essentially all reason to use Microsoft's "text" macros like _T("whatever"). If you want wide characters, ask for them directly:

CFont font;   
font.CreatePointFont(nFontHeight, L"Courier New");

Then, as suggested by @MikMik, you can use GetTextMetrics to get the width -- but only after you select the font into a DC (GetTextMetrics gets the data for a font selected into a DC, not just for the raw font -- especially at small font sizes, some things get adjusted to compensate for the resolution of the output device).

Note, however, that even for a fixed-width font, the width of a string is not necessarily char_width * num_chars. At least if I recall correctly, even a fixed-width font can still be kerned, which means the spacing is adjusted based on what pairs of characters occur together. The classic example is a pair like AV. Because the lines where they're next to each other are typically at the same angle (or at least very close to the same) the spacing will be adjusted to move them closer together -- in fact, the top of the "V" will often overlap with the bottom of the "A". The width of a string of characters can vary even though each individual character has the same width as every other.

Offhand, I'm not sure that Courier New does that, but I'm reasonably certain at least a few fixed-width fonts do.


Have you tried CDC::GetTextMetrics()? I've never used it, but it seems to be what you're looking for. You can get the average and maximum character width, which I guess should be the same for Courier New.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜