LPD3DXFONT m_font;
// Create a D3DX font object
D3DXCreateFont( gD3dDevice, 20, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, TEXT("Arial"), &m_font );
void DisplaySomeText()
{
// Create a colour for the text - in this case blue
D3DCOLOR fontColor = D3DCOLOR_ARGB(255,0,0,255);
// Create a rectangle to indicate where on the screen it should be drawn
RECT rct;
rct.left=2;
rct.right=780;
rct.top=10;
rct.bottom=rct.top+20;
// Draw some text
m_font->DrawText(NULL, "Hello World", -1, &rct, 0, fontColor );
}
The format of the draw call is:
int DrawText( LPD3DXSPRITE pSprite, LPCTSTR pString, INT Count, LPRECT pRect, DWORD Format, D3DCOLOR Color );
* pSprite - the first parameter allows a sprite interface to be passed in. Setting this to NULL means Direct3D will use its own internal sprite object to render the text. If you are doing lots of DrawText calls passing your own sprite object can speed up rendering significantly (see font drawing optimisations below).
* pString - this is the string to render. The type of string depends on your projects character set.
* Count - the number of characters in the string. You can set this to the magic number -1 in order to specify that Direct3D should count the characters itself. Note that this only works with null terminated strings.
* pRect - the rectangular area in which the text will be displayed. How the text is justified within this rectangle depends on the next parameter:
* Format - allows you to specify some flags. This allows you to specify the justification of the text within the rectangle plus some other options (see advanced below).
* Color - the final parameter is the colour you want to render the text.
As always you must release the D3DX interface before your program exits or on a device reset:
m_font->Release();
The third parameter to the DrawText function is a flag that allows you to specify justification etc. There is also a very useful flag: DT_CALCRECT that causes DrawText to set the passed rectangle to the size required to display the text. When using this flag DrawText will not actually draw anything, it is purely a way of obtaining the size of the text.
Font Drawing Optimisations
Text drawing can be slow and so there are a couple of optimisations provided by the font interface. Unfortunately these are not very well documented so I decided to carry out some tests of my own to determine some real world values.
I found that passing a sprite object as the first parameter to DrawText improved rendering speeds by up to 4 times - quite a significant improvement.
The sprite interface also provides a function to allow you to preload a text string into video card memory - PreloadText. This should theoretically improve performance as the function would not need to assemble the characters each time and upload them to the graphic card. However from my test results I found little speed improvement.