Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get text width (DirectX, C++)

Tags:

c++

text

directx

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.

like image 426
Freakyy Avatar asked Nov 24 '13 17:11

Freakyy


1 Answers

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.

like image 116
Roger Rowland Avatar answered Oct 08 '22 18:10

Roger Rowland