# string width

This topic is 4731 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

how would i determine the width of a string or character (in pixels) in c++. i've been trying to use GetCharWidth but i don't trust it since it doesn't ask for what font you're using.

##### Share on other sites
Check in the MSDN.

Notice it suggests you use GetCharWidth32, and that you should use GetCharABCWidths if you want to get the width of TrueType fonts.

The question about selecting your font - it uses the font currently selected in the device context (first parameter to those functions is a HDC - handle to a device context). See SelectObject and CreateFont to select a font into your device context.

##### Share on other sites
Using the default MAPPING MODE (pixels), I obtain a character width by doing the following:

In C:
int iCharWidth;GetCharWidth32((UNIT)'A', (UINT)'A', &iCharWidth);iCharWidth *= 2; // you multiply by 2 to convert to pixel units.

To get a string width, I don't know as I have'nt had the need to do so yet.
But I think GetCharABCWidthsFloat might be able to help you here. Try it and see.

relient.

##### Share on other sites
Adding the width of each character will not get your the size of the string in pixels, because of kerning.

To get the size of a string, use GetTextExtentPoint32:

const char *text = "Hello world!";POINT size;GetTextExtentPoint32 (hdc, text, strlen (text), &size);

The result is in logical units which (for a device context associated with the display rather than, say, a printer) means pixels, unless you've changed it using SetMapMode (hdc, /*something other than MM_TEXT*/);.

• 10
• 17
• 9
• 13
• 41