Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the width of a String (in pixels) in WIN32

Can you measure the width of a string more exactly in WIN32 than using the GetTextMetrics function and using tmAveCharWidth*strSize?

like image 561
Razvi Avatar asked Jul 14 '09 17:07

Razvi


People also ask

How do you find the width of a string in C++?

The C++ String class has length() and size() function. These can be used to get the length of a string type object. To get the length of the traditional C like strings, we can use the strlen() function.

Which function is used to return the width of a string in pixels?

textwidth() function in C h contains textwidth () function which returns the width of input string in pixels.

How do I get text size in C++?

You can get the length of a string object by using a size() function or a length() function. The size() and length() functions are just synonyms and they both do exactly same thing.


2 Answers

I don't know for certain, but it seems that:

HDC hDC = GetDC(NULL);
RECT r = { 0, 0, 0, 0 };
char str[] = "Whatever";
DrawText(hDC, str, strlen(str), &r, DT_CALCRECT);

might work.

like image 22
Evan Teran Avatar answered Sep 23 '22 10:09

Evan Teran


Try using GetTextExtentPoint32. That uses the current font for the given device context to measure the width and height of the rendered string in logical units. For the default mapping mode, MM_TEXT, 1 logical unit is 1 pixel.

However, if you've changed the mapping mode for the current device context, a logical unit may not be the same as a pixel. You can read about the different mapping modes on MSDN. With the mapping mode, you can convert the dimensions returned to you by GetTextExtentPoint32 to pixels.

like image 131
Nick Meyer Avatar answered Sep 22 '22 10:09

Nick Meyer