D3D中的字体绘制示例

摘要:
技巧如下:字体的绘制需要使用ID3DXFont对象和D3DXCreateFontIndirect函数。DirectXSDK文档对ID3DXFont做了简要的说明:TheID3DXFontinterfaceencapsulatesthetexturesandresourcesneededtorenderaspecificfontonaspecificdevice.TheID3DXFontinterf
技巧如下:
字体的绘制需要使用ID3DXFont对象和 D3DXCreateFontIndirect函数。
DirectX SDK文档对ID3DXFont做了简要的说明:
The ID3DXFont interface encapsulates the textures and resources needed to render a specific font on a specific device.
The ID3DXFont interface is obtained by calling D3DXCreateFont or D3DXCreateFontIndirect.
我们来看看SDK文档提供的关于 D3DXCreateFontIndirect的使用说明:

Creates a font object indirectly for both a device and a font.

HRESULT D3DXCreateFontIndirect(
LPDIRECT3DDEVICE9 pDevice,
CONST D3DXFONT_DESC * pDesc,
LPD3DXFONT * ppFont
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device to be associated with the font object.
pDesc
[in] Pointer to a D3DXFONT_DESC structure, describing the attributes of the font object to create. If the compiler settings require Unicode, the data type D3DXFONT_DESC resolves to D3DXFONT_DESCW; otherwise, the data type resolves to D3DXFONT_DESCA. See Remarks.
ppFont
[out] Returns a pointer to an ID3DXFont interface, representing the created font object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, E_OUTOFMEMORY.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateFontIndirectW. Otherwise, the function call resolves to D3DXCreateFontIndirectA because ANSI strings are being used.
该函数的第二个参数使用了一个结构体D3DXFONT_DESC,来看看它的具体定义:

Defines the attributes of a font.

typedef struct D3DXFONT_DESC {
INT Height;
UINT Width;
UINT Weight;
UINT MipLevels;
BOOL Italic;
BYTE CharSet;
BYTE OutputPrecision;
BYTE Quality;
BYTE PitchAndFamily;
TCHAR FaceName[LF_FACESIZE];
} D3DXFONT_DESC, *LPD3DXFONT_DESC;

Members

Height
Height, in logical units, of the font's character cell or character.
Width
Width, in logical units, of characters in the font.
Weight
Weight of the font in the range from 0 through 1000.
MipLevels
Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created. If the value is 1, the texture space is mapped identically to the screen space.
Italic
Set to TRUE for an Italic font.
CharSet
Character set.
OutputPrecision
Output precision. The output precision defines how closely the output must match the requested font height, width, character orientation, escapement, pitch, and font type.
Quality
Output quality.
PitchAndFamily
Pitch and family of the font.
FaceName
A null-terminated string or characters that specifies the typeface name of the font. The length of the string must not exceed 32 characters, including the terminating null character. If FaceName is an empty string, the first font that matches the other specified attributes will be used. If the compiler settings require Unicode, the data type TCHAR resolves to WCHAR; otherwise, the data type resolves to CHAR. See Remarks.

Remarks

The compiler setting also determines the structure type. If Unicode is defined, the D3DXFONT_DESC structure type resolves to a D3DXFONT_DESCW; otherwise the structure type resolves to a D3DXFONT_DESCA.

Possible values of the above members are given in the GDI LOGFONT structure.
当然,在设置的时候我们不需要设置所有的属性,只要设置其中的几个主要属性就可以了。
我们可以这样设置字体的属性并创建字体:

D3DXFONT_DESCfont_desc;
//createthefont
ZeroMemory(&font_desc,sizeof(font_desc));
//setfontdescripter
strcpy(font_desc.FaceName,"Arial");
font_desc.Height=32;
//Createsafontobjectindirectlyforbothadeviceandafont
D3DXCreateFontIndirect(g_d3d_device,&font_desc,&g_font);

通过ID3DXFont::DrawText方法我们可以绘制字体了,来看看它的具体使用信息:

Draws formatted text. This method supports ANSI and Unicode strings.

INT DrawText(
LPD3DXSPRITE pSprite,
LPCTSTR pString,
INT Count,
LPRECT pRect,
DWORD Format,
D3DCOLOR Color
);

Parameters

pSprite
[in] Pointer to an ID3DXSprite object that contains the string. Can be NULL, in which case Direct3D will render the string with its own sprite object. To improve efficiency, a sprite object should be specified if ID3DXFont::DrawText is to be called more than once in a row.
pString
[in] Pointer to a string to draw.If the Count parameter is -1, the string must be null-terminated.
Count
[in] Specifies the number of characters in the string. If Count is -1, then the pString parameter is assumed to be a pointer to a null-terminated string and ID3DXFont::DrawText computes the character count automatically.
pRect
[in] Pointer to a RECT structure that contains the rectangle, in logical coordinates, in which the text is to be formatted. As with any RECT object, the coordinate value of the rectangle's right side must be greater than that of its left side. Likewise, the coordinate value of the bottom must be greater than that of the top.
Format
[in] Specifies the method of formatting the text. It can be any combination of the following values:
DT_BOTTOM
Justifies the text to the bottom of the rectangle. This value must be combined with DT_SINGLELINE.
DT_CALCRECT
Determines the width and height of the rectangle. If there are multiple lines of text, ID3DXFont::DrawText uses the width of the rectangle pointed to by the pRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, ID3DXFont::DrawText modifies the right side of the rectangle so that it bounds the last character in the line. In either case, ID3DXFont::DrawText returns the height of the formatted text but does not draw the text.
DT_CENTER
Centers text horizontally in the rectangle.
DT_EXPANDTABS
Expands tab characters. The default number of characters per tab is eight.
DT_LEFT
Aligns text to the left.
DT_NOCLIP
Draws without clipping. ID3DXFont::DrawText is somewhat faster when DT_NOCLIP is used.
DT_RIGHT
Aligns text to the right.
DT_RTLREADING
Displays text in right-to-left reading order for bidirectional text when a Hebrew or Arabic font is selected. The default reading order for all text is left-to-right.
DT_SINGLELINE
Displays text on a single line only. Carriage returns and line feeds do not break the line.
DT_TOP
Top-justifies text.
DT_VCENTER
Centers text vertically (single line only).
DT_WORDBREAK
Breaks words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the pRect parameter. A carriage return/line feed sequence also breaks the line.
Color
[in] Color of the text. For more information, see D3DCOLOR.

Return Values

If the function succeeds, the return value is the height of the text in logical units. If DT_VCENTER or DT_BOTTOM is specified, the return value is the offset from pRect (top to the bottom) of the drawn text. If the function fails, the return value is zero.

Remarks

The parameters of this method are very similar to those of the GDI DrawText function.

This method supports both ANSI and Unicode strings.

This method must be called inside a IDirect3DDevice9::BeginScene ... IDirect3DDevice9::EndScene block. The only exception is when an application calls ID3DXFont::DrawText with DT_CALCRECT to calculate the size of a given block of text.

Unless the DT_NOCLIP format is used, this method clips the text so that it does not appear outside the specified rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is specified.

If the selected font is too large for the rectangle, this method does not attempt to substitute a smaller font.

This method supports only fonts whose escapement and orientation are both zero.

我们可以这样使用该函数:

RECTrect={0,0,WINDOW_WIDTH,WINDOW_HEIGHT};
//Beginscene
if(SUCCEEDED(g_d3d_device->BeginScene()))
{
//drawsometext
g_font->DrawTextA(NULL,"Programmingisfun!",-1,&rect,DT_CENTER|DT_VCENTER,0xFFFFFFFF);
//endthescene
g_d3d_device->EndScene();
}

完整源码如下:
/***************************************************************************************
PURPOSE:
FontDemo
Requiredlibraries:
D3D9.LIBandD3DX9.LIB
***************************************************************************************/

#include<windows.h>
#include<stdio.h>
#include"d3d9.h"
#include"d3dx9.h"
#pragmacomment(lib,"d3d9.lib")
#pragmacomment(lib,"d3dx9.lib")
#pragmawarning(disable:4996)
#defineWINDOW_WIDTH400
#defineWINDOW_HEIGHT400
#defineSafe_Release(p)if((p))(p)->Release();
//windowhandles,classandcaptiontext.
HWNDg_hwnd;
HINSTANCEg_inst;
staticcharg_class_name[]="FontClass";
staticcharg_caption[]="FontDemo";
//theDirect3Danddeviceobject
IDirect3D9*g_d3d=NULL;
IDirect3DDevice9*g_d3d_device=NULL;
//thefontobject
ID3DXFont*g_font=NULL;
//--------------------------------------------------------------------------------
//Windowprocedure.
//--------------------------------------------------------------------------------
longWINAPIWindow_Proc(HWNDhwnd,UINTmsg,WPARAMwParam,LPARAMlParam)
{
switch(msg)
{
caseWM_DESTROY:
PostQuitMessage(0);
return0;
}
return(long)DefWindowProc(hwnd,msg,wParam,lParam);
}
//--------------------------------------------------------------------------------
//Initialized3d,d3ddevice,vertexbuffer,texutre.
//--------------------------------------------------------------------------------
BOOLDo_Init()
{
D3DPRESENT_PARAMETERSpresent_param;
D3DDISPLAYMODEdisplay_mode;
D3DXFONT_DESCfont_desc;
//doawindowedmodeinitializationofDirect3D
if((g_d3d=Direct3DCreate9(D3D_SDK_VERSION))==NULL)
returnFALSE;
//retrievesthecurrentdisplaymodeoftheadapter
if(FAILED(g_d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,&display_mode)))
returnFALSE;
ZeroMemory(&present_param,
sizeof(present_param));
//initialized3dpresentationparameter
present_param.Windowed=TRUE;
present_param.SwapEffect=D3DSWAPEFFECT_DISCARD;
present_param.BackBufferFormat=display_mode.Format;
//createsadevicetorepresentthedisplayadapter
if(FAILED(g_d3d->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,g_hwnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,&present_param,&g_d3d_device)))
returnFALSE;
//createthefont
ZeroMemory(&font_desc,sizeof(font_desc));
//setfontdescripter
strcpy(font_desc.FaceName,"Arial");
font_desc.Height=32;
//Createsafontobjectindirectlyforbothadeviceandafont
D3DXCreateFontIndirect(g_d3d_device,&font_desc,&g_font);
returnTRUE;
}
//--------------------------------------------------------------------------------
//Releasealld3dresource.
//--------------------------------------------------------------------------------
BOOLDo_Shutdown()
{
Safe_Release(g_font);
Safe_Release(g_d3d_device);
Safe_Release(g_d3d);
returnTRUE;
}
//--------------------------------------------------------------------------------
//Renderaframe.
//--------------------------------------------------------------------------------
BOOLDo_Frame()
{
RECTrect={0,0,WINDOW_WIDTH,WINDOW_HEIGHT};
//cleardevicebackbuffer
g_d3d_device->Clear(0,NULL,D3DCLEAR_TARGET,D3DCOLOR_RGBA(0,64,128,255),1.0f,0);
//Beginscene
if(SUCCEEDED(g_d3d_device->BeginScene()))
{
//drawsometext
g_font->DrawTextA(NULL,"Programmingisfun!",-1,&rect,DT_CENTER|DT_VCENTER,0xFFFFFFFF);
//endthescene
g_d3d_device->EndScene();
}
//presentthecontentsofthenextbufferinthesequenceofbackbuffersownedbythedevice
g_d3d_device->Present(NULL,NULL,NULL,NULL);
returnTRUE;
}
//--------------------------------------------------------------------------------
//Mainfunction,routineentry.
//--------------------------------------------------------------------------------
intWINAPIWinMain(HINSTANCEinst,HINSTANCE,LPSTRcmd_line,intcmd_show)
{
WNDCLASSEXwin_class;
MSGmsg;
g_inst=inst;
//createwindowclassandregisterit
win_class.cbSize=sizeof(win_class);
win_class.style=CS_CLASSDC;
win_class.lpfnWndProc=Window_Proc;
win_class.cbClsExtra=0;
win_class.cbWndExtra=0;
win_class.hInstance=inst;
win_class.hIcon=LoadIcon(NULL,IDI_APPLICATION);
win_class.hCursor=LoadCursor(NULL,IDC_ARROW);
win_class.hbrBackground=NULL;
win_class.lpszMenuName=NULL;
win_class.lpszClassName=g_class_name;
win_class.hIconSm=LoadIcon(NULL,IDI_APPLICATION);
if(!RegisterClassEx(&win_class))
returnFALSE;
//createthemainwindow
g_hwnd=CreateWindow(g_class_name,g_caption,WS_CAPTION|WS_SYSMENU,0,0,
WINDOW_WIDTH,WINDOW_HEIGHT,NULL,NULL,inst,NULL);
if(g_hwnd==NULL)
returnFALSE;
ShowWindow(g_hwnd,SW_NORMAL);
UpdateWindow(g_hwnd);
//initializegame
if(Do_Init()==FALSE)
returnFALSE;
//startmessagepump,waitingforsignaltoquit.
ZeroMemory(&msg,sizeof(MSG));
while(msg.message!=WM_QUIT)
{
if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
//drawaframe
if(Do_Frame()==FALSE)
break;
}
//runshutdownfunction
Do_Shutdown();
UnregisterClass(g_class_name,inst);
return(int)msg.wParam;
}

效果图如下:
D3D中的字体绘制示例第1张
转载:http://www.cppblog.com/lovedday/archive/2007/07/03/27434.html

免责声明:文章转载自《D3D中的字体绘制示例》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇mysql db [Warning] IP address 'xxxx' could not be resolved: Name or service not knownkafka的分区分配策略下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

c# zxing生成二维码和打印

生成二维码代码 asset=“要生成的字符串”; public static Bitmap CreateQRCode(string asset) { EncodingOptions options = new QrCodeEncodingOptions { DisableECI = true,...

QT中文字的绘制

为什么要做这次文字的介绍,因为在一般的教材中,还真没有文字的描述: 1.绘制最简单的文字。 我们更改重绘函数如下: void Dialog::paintEvent(QPaintEvent *){QPainter painter(this);painter.drawText(100,100,”yafeilinux”);} 我们在(100,100)的位置显示了...

中文标准web字体

标准的简体中文web字体: Windows OS X 黑体:SimHei 冬青黑体: Hiragino Sans GB [NEW FOR SNOW LEOPARD] 宋体:SimSun 华文细黑:STHeiti Light [STXihei] 新宋体:NSimSun 华文黑体:STHeiti 仿宋:FangSong 华文楷体:STKa...

php FPDF类库应用实现代码

<?php require('chinese.php'); class PDF extends PDF_Chinese { function Header() //设置页眉 { $this->SetFont('GB','',10); $this->Write(10,'XX公司产品名录'); $this->Ln(20...

CSS实现横向滑动

html <div class="header1"> <div class="header-nei"> <div>第一场</div> <div>第二场</div> <div>第三场</div> <div>第四场</div>...

MarkDown语言

目录 1、Markdown简介 2、辅助线 1)中划线语法 2)下划线语法 3、字体、字号 1)改变字体 (1)修改局部字体 (2)常用字体 2)改变字号 (1)使用 标签 size 属性修改局部字号 (2)使用 和 标签修改局部字号 3)全局字体、字号的设置 4、前背景、背景色 1)前背景 2)背景色 3)图片背景色...