How to get text width (DirectX, C++)
Asked Answered
H

1

5

I'm working on a GUI-Project with d3d9 & d3dx9. I create fonts using the D3DXCreateFont function (C++). Everything is working fine. But I need a function that determines the width in pixel for a specific text.

Something like this:

char text[64] = "Heyho - Blablabla";
GUIFont* hFont = gui->fonts->CreateFont("DefaultFont", "Arial", 18);
int width = hFont->GetTextWidth(text);
[...]

The part with gui->fonts->CreateFont is all working fine. It's my way of creating and storing fonts. Ignore that part, it's all about the GetTextWidth. My CreateFont function initalizes the GUIFont object. The actual D3D-Font is stored in a LPD3DXFONT.

I really hope you can help me with this one, I am pretty sure it's possible - I just don't know how. Thanks for reading, and I hope you have a clue.

Hildahildagard answered 24/11, 2013 at 17:50 Comment(0)
N
9

You can use the DT_CALCRECT flag on the ID3DXFont function DrawText to return the required size of the rectangle enclosing the text.

So, if you want to get just the width, you might have a function something like this:

int GetTextWidth(const char *szText, LPD3DXFont pFont)
{
    RECT rcRect = {0,0,0,0};
    if (pFont)
    {
        // calculate required rect
        pFont->DrawText(NULL, szText, strlen(szText), &rcRect, DT_CALCRECT,
                    D3DCOLOR_XRGB(0, 0, 0));
    }

    // return width
    return rcRect.right - rcRect.left;
}

Obviously, you can also extract the height too if you need it.

Nectareous answered 25/11, 2013 at 7:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.