The following example measures the size of a string and then draws a rectangle that represents that size.
C++
VOID Example_MeasureString2(HDC hdc)
{
Graphics graphics(hdc);
// Set up the string.
WCHAR string[] = L"Measure Text";
Font font(L"Arial", 16);
RectF layoutRect(0.0f, 0.0f, 100.0f, 50.0f);
StringFormat format;
format.SetAlignment(StringAlignmentFar);
RectF boundRect;
// Measure the string.
graphics.MeasureString(string, 12, &font, layoutRect, &format, &boundRect);
// Draw a rectangle that represents the size of the string.
graphics.DrawRectangle(&Pen(Color(255, 0, 0, 0)), boundRect);
}
PowerBASIC
SUB GDIP_MeasureString (BYVAL hdc AS DWORD)
LOCAL hStatus AS LONG
LOCAL pGraphics AS DWORD
LOCAL pPen AS DWORD
LOCAL pFont AS DWORD
LOCAL pFontFamily AS DWORD
LOCAL pFormat AS DWORD
LOCAL strFontName AS STRING
LOCAL strText AS STRING
LOCAL layoutRect AS RECTF
LOCAL boundRect AS RECTF
hStatus = GdipCreateFromHDC(hdc, pGraphics)
' // Create the font
strFontName = UCODE$("Arial")
hStatus = GdipCreateFontFamilyFromName(STRPTR(strFontName), %NULL, pFontFamily)
IF hStatus = %StatusOk AND pFontFamily <> %NULL THEN
hStatus = GdipCreateFont(pFontFamily, 16, %FontStyleRegular, %UnitPoint, pFont)
GdipDeleteFontFamily(pFontFamily)
END IF
' Note: You can use the wrapper function GdiPlusCreateFontFromName to create the font:
' hStatus = GdiPlusCreateFontFromName("Arial", 16, %FontStyleRegular, %UnitPoint, pFont)
' // Setup the string
strText = UCODE$("Measure Text")
layoutRect.x = 0.0! : layoutRect.y = 0.0! : layoutRect.Width = 100.0! : layoutRect.Height = 50.0!
hStatus = GdipCreateStringFormat(0, %LANG_NEUTRAL, pFormat)
hStatus = GdipSetStringFormatAlign(pFormat, %StringAlignmentFar)
' // Measure the string
hStatus = GdipMeasureString(pGraphics, STRPTR(strText), LEN(StrText) \ 2, pFont, layoutRect, pFormat, boundRect, 0, 0)
' // Draw a rectangle that represents the size of the string.
' // Create a Pen
hStatus = GdipCreatePen1(GDIP_ARGB(255, 0, 0, 0), 1, %UnitPixel, pPen)
hStatus = GdipDrawRectangle(pGraphics, pPen, boundRect.x, boundRect.y, boundRect.Width, boundRect.Height)
' // Cleanup
IF pFont THEN GdipDeleteFont(pFont)
IF pPen THEN GdipDeletePen(pPen)
IF pFormat THEN GdipDeleteStringFormat(pFormat)
IF pGraphics THEN GdipDeleteGraphics(pGraphics)
END SUB
(http://www.jose.it-berater.org/captures/GdipMeasureString.png)