本程序?qū)崿F(xiàn)在對話框界面上以Windows系統(tǒng)字體轉(zhuǎn)為點陣的形式顯示字符或漢字
新建對話框程序:
1.加入成員變量:
byte* m_pBuf; //子體數(shù)據(jù)緩沖區(qū)
int m_nWidth;//字體實際寬度
int m_nHeight;//字體實際高度
2.加入成員函數(shù):
void freeData()
{
if ( m_pBuf )
{
free( m_pBuf );
m_pBuf = NULL;
}
}
//浮點數(shù)據(jù)轉(zhuǎn)換為固定浮點數(shù)。
FIXED FixedFromDouble(double d)
{
long l;
l = (long) (d * 65536L);
return *(FIXED *)&l;
}
//設(shè)置字體圖形變換矩陣。
void SetMat(LPMAT2 lpMat)
{
lpMat->eM11 = FixedFromDouble(2);
lpMat->eM12 = FixedFromDouble(0);
lpMat->eM21 = FixedFromDouble(0);
lpMat->eM22 = FixedFromDouble(2);
}
3.構(gòu)造函數(shù)中加入:
m_pBuf = NULL;
m_nWidth = 0;
m_nHeight = 0;
4.析構(gòu)函數(shù)中加入:
freeData();
5.定制一按鈕實現(xiàn)如下代碼:
CFontDialog dlg;
if ( IDOK == dlg.DoModal())
{
LOGFONT lf;
dlg.GetCurrentFont( &lf );
//創(chuàng)建字體。
HFONT hFont = CreateFontIndirect( &lf) ;
CFont* pFont = CFont::FromHandle( hFont );
//設(shè)置字體到當前設(shè)備。
CDC*pDC = GetDC();
CFont* pOldFont = pDC->SelectObject( pFont );
//設(shè)置字體圖形變換矩陣
MAT2 mat2;
SetMat(&mat2);
GLYPHMETRICS gm;
//設(shè)置要顯示的字符。
//TCHAR ch =
L'@';
TCHAR ch = L'章';
//獲取這個字符圖形需要的字節(jié)的大小。
DWORD dwNeedSize = pDC->GetGlyphOutline(ch,GGO_BITMAP,&gm,0,NULL,&mat2);
if (dwNeedSize > 0 && dwNeedSize < 0xFFFF)
{
freeData();
m_pBuf = (byte*)(malloc(dwNeedSize));
if ( m_pBuf)
{
//獲取字符圖形的數(shù)據(jù)到緩沖區(qū)。
pDC->GetGlyphOutline(ch,GGO_BITMAP,&gm,dwNeedSize,m_pBuf,&mat2);
m_nWidth = gm.gmBlackBoxX;
m_nHeight = gm.gmBlackBoxY;
//下面只是為了在調(diào)試窗查看數(shù)據(jù),可以不要
//////////////////////////////////////////////////////////////////////////
/* //計算圖形每行占用的字節(jié)數(shù)。
int nByteCount = ((gm.gmBlackBoxX +31) >> 5) << 2;
//顯示每行圖形的數(shù)據(jù)。
for (int i = 0; i < gm.gmBlackBoxY; i++)
{
for (int j = 0; j < nByteCount; j++)
{
BYTE btCode = m_pBuf[i* nByteCount + j];
CString str;
str.Format( _T("%x "),btCode );
OutputDebugString( str );
//按字節(jié)輸出每點的數(shù)據(jù)。
// for (int k = 0; k < 8; k++)
// {
// if (btCode & (0x80>>k))
// {
// OutputDebugString(_T("1"));
// }
// else
// {
// OutputDebugString(_T("0"));
// }
// }
}
OutputDebugString(_T("\r\n"));
} */
//////////////////////////////////////////////////////////////////////////
}
Invalidate( TRUE );
}
pDC->SelectObject(pOldFont);
DeleteObject(hFont);
ReleaseDC(pDC);
}
6.在對話款的OnPaint函數(shù)中的CDialog::OnPaint()前面實現(xiàn)如下代碼:
if(m_pBuf != NULL)
{
CPaintDC dc(this); // 用于繪制的設(shè)備上下文
CRect rect;
GetClientRect(&rect);
int x = rect.left + 10;
int y = rect.top + 10;
int dx = 0;
int dy = 0;
int dsize = 10;
byte* pStr = m_pBuf;
//計算圖形每行占用的字節(jié)數(shù)(4字節(jié)對齊)
int nLen = ((m_nWidth +31) >> 5) << 2;
for( int j=0; j<m_nHeight; j++)
{
dy = y + j * dsize;
for(int i=0; i<nLen; i++)
{
dx = x + i * 8 * dsize;
byte val = *pStr;
for( int bit=0; bit<8 ; bit++)
{
dc.FillSolidRect(dx, dy, dsize, dsize, (val & (0x80 >> bit)) ? RGB(0,0,0) : RGB(255,255,255));
dx = dx + dsize;
}
pStr++;
}
}
}
注意:顯示漢字字體時要采用 Unicode 字符集編碼。