Razvi
Razvi

Reputation: 2818

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?

Upvotes: 18

Views: 37752

Answers (5)

Evan Teran
Evan Teran

Reputation: 90563

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.

Upvotes: 19

For Builder C++ first make new TLabel dynamicly and then change font attributes.Set your TLabel as autosize.Then you can get you TLabel width witch represents your string width in pixels.

 int WidthPixels (String font, int size, String text)
 {
    TLabel* label = new TLabel(Form1); // dynamic TLabel
    label->AutoSize = true;
    label->Font->Name = font; // your font
    label->Font->Size = size; // your font size
    label->Caption = text; // your string
    return label->Width;
 }

int width = WidthPixels("Times New Roman", 19 , "Hey");

Upvotes: 0

Nick Meyer
Nick Meyer

Reputation: 40422

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.

Upvotes: 24

DeusAduro
DeusAduro

Reputation: 6076

Depending on how you are using this, you can use DrawText with DT_CALCRECT specified and it will (its always done it fairly accurately for me) calculate the size of the required rectangle based on the text/font/etc.

Upvotes: 1

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99725

Graphics::MeasureString ?

VOID Example_MeasureString(HDC hdc)
{
   Graphics graphics(hdc);
   // Set up the string.
   WCHAR string[] = L"Measure Text";
   Font font(L"Arial", 16);
   RectF layoutRect(0, 0, 100, 50);
   RectF boundRect;
   // Measure the string.
   graphics.MeasureString(string, 12, &font, layoutRect, &boundRect);
   // Draw a rectangle that represents the size of the string.
   graphics.DrawRectangle(&Pen(Color(255, 0, 0, 0)), boundRect);
}

Upvotes: 5

Related Questions