15,979
社区成员
发帖
与我相关
我的任务
分享
void CalcCharSize(HDC hDC, TCHAR ch, SIZE &siSize, SIZE *pTB)
{
GetTextExtentPoint32(hDC, &ch, 1, &siSize);
int iWidth = siSize.cx;
int iHeight = siSize.cy;
//设备无关位图
CONST int BIT_COUNT24 = 24;
BITMAPINFO bmpInfo={0};
int bmpWidthBytes =0;
bmpWidthBytes= iWidth*BIT_COUNT24;//4字节对齐,位图每一行数据的大小.
bmpWidthBytes+=31;
bmpWidthBytes/=32;
bmpWidthBytes*=4;
ZeroMemory(&bmpInfo,sizeof(BITMAPINFO));
bmpInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
bmpInfo.bmiHeader.biBitCount=BIT_COUNT24;
bmpInfo.bmiHeader.biCompression=BI_RGB;
bmpInfo.bmiHeader.biPlanes=1;
bmpInfo.bmiHeader.biWidth=iWidth;
bmpInfo.bmiHeader.biHeight=-iHeight;
bmpInfo.bmiHeader.biSizeImage = bmpWidthBytes * iHeight;
BYTE *pBmpBits=NULL;
HBITMAP hBmp=::CreateDIBSection(NULL,&bmpInfo,0,(void**)&pBmpBits,NULL,0);
HDC hMemDC = CreateCompatibleDC(hDC);
HBITMAP hOldBmp = (HBITMAP)::SelectObject(hMemDC, hBmp);
SetBkMode(hMemDC, TRANSPARENT);
//设置目标颜色, 方便下面计算
SetTextColor(hMemDC, RGB(255,255,255));
//统一字体
HFONT hFont = (HFONT)::GetCurrentObject(hDC, OBJ_FONT);
HFONT hOldFont = (HFONT)::SelectObject(hMemDC, hFont);
RECT rcRect = {0,0,siSize.cx, siSize.cy};
DrawText(hMemDC, &ch, 1, &rcRect, DT_LEFT|DT_TOP);
::SelectObject(hMemDC, hOldFont);
//找top
int top = 0;
for(int y=0; y<iHeight; ++y)
{
for(int x=0; x<iWidth; ++x)
{
if(pBmpBits[y*bmpWidthBytes+x*3] > 0)
{
top = y;
y = iHeight;
break;
}
}
}
//找bottom
int bottom = 0;
for(int y=iHeight-1; y>0; --y)
{
for(int x=0; x<iWidth; ++x)
{
if(pBmpBits[y*bmpWidthBytes+3*x] > 0)
{
bottom = y;
y = 0;
break;
}
}
}
if(pTB)
{
pTB->cx = top;
pTB->cy = siSize.cy-bottom-1;
}
siSize.cy = bottom-top+1;
::SelectObject(hMemDC, hOldBmp);
::DeleteObject(hBmp);
::DeleteDC(hMemDC);
}
void CdlgDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CFont ft;
ft.CreateFont(
100, // nHeight
0, // nWidth
0, // nEscapement
0, // nOrientation
0, // nWeight
FALSE, // bItalic
FALSE, // bUnderline
0, // cStrikeOut
ANSI_CHARSET, // nCharSet
OUT_DEFAULT_PRECIS, // nOutPrecision
CLIP_DEFAULT_PRECIS, // nClipPrecision
DEFAULT_QUALITY, // nQuality
DEFAULT_PITCH | FF_SWISS, // nPitchAndFamily
L"宋体");
CPaintDC dc(this); // 用于绘制的设备上下文
dc.SelectObject( ft );
CString str = L"jklHJK弹簧";
CRect rc;
dc.DrawText( str, rc, DT_CALCRECT );
rc.OffsetRect( 10, 10 );
dc.Rectangle(rc);
dc.DrawText( str, rc, DT_LEFT);
}
}