Question

In my software written for Windows with Builder C++ 6, I need to create a .pdf article with some information the user edit and is stored in a database. Part of this information must be drawn inside a designed rect, so I need to check whatever the 55max character string will fit with just one line inside the rect. If not, than I need to calculate where I should give a new line (\n).

Normally texts do fit inside the rect having only 55 characters, but sometimes some uncommon text (such as "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW..."), while having the same amount of characters, end up messing the whole thing. In other words, I can't use the number of characters in the string to determinate when to give a new line, but rather the text's length in pixels (or other measure unit), so I can check whatever the string will be bigger in the .pdf that it's rect container or not.

I tried functions such as GetCharABCWidths(), GetTextExtentPoint32(), but had no success (either the so called "logical units" ere different each time I used the function for the same string/char and I didn't know how to use them, or the length of the char was equal even when they were obviously different ('1' compared to 'W'), or something else).

So how can I do this?

Was it helpful?

Solution

At the end, I was able to do what I wanted using this typ from Length of a string in pixels:

To get a more accurate measurement, you can populate a TextField with the string, then measure the width of that TextField's text.

That went me back to Borland C++ Builder where I found a function (Canvas->TextExtent) that tells how much the String is goign to occupy in the canvas.

So, problem solved!

OTHER TIPS

You can also use the DrawText function. Just pass the DT_CALCRECT flag to the function. Or even GetTextMetrics - I've used both here. They're plain, vanilla win32 functions. Works in any compiler supporting win32 progs that you wish to try. VS, GCC, Borland, etc.

CODE snippet:

HDC hDC;
TEXTMETRIC textMetric;
HFONT   hFont, hOldFont;
int sizeInPpoints, lineHeight;
RECT textRect;
char *buffer = "Comprimento em pixels desta string!";

hDC = GetDC(hwnd);
sizeInPpoints = MulDiv(10, GetDeviceCaps(hDC, LOGPIXELSY), 72);
hFont = CreateFont(-sizeInPpoints, 0, 0, 0, FW_NORMAL, 0, 0, 0, 0, 0, 0, 0, 0, "Courier New");
hOldFont = (HFONT)SelectObject(hDC, hFont);

GetTextMetrics(hDC, &textMetric);

lineHeight = textMetric.tmHeight; // character height in current font

textRect.left = textRect.right = textRect.top = textRect.bottom = 0;
DrawText(hDC, buffer, strlen(buffer), &textRect, DT_CALCRECT);

printf("Size of text calculated by DrawText: [%d x %d]\n", textRect.right, textRect.bottom);
printf("Height of text calculated by GetTextMetrics: %d\n", lineHeight);

Output:

Size of text calculated by DrawText: [280 x 16]
Height of text calculated by GetTextMetrics: 16
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top