VC中精确获取字符串长宽

void CTestDlg::OnButton1()

{

     // TODO: Add your control notification handler code here

     CDC* pDC;

    

     LOGFONT tLogFont;

     tLogFont.lfHeight = 21;

     tLogFont.lfWidth  = 0;

     tLogFont.lfEscapement = 0;

     tLogFont.lfOrientation = 0;

     tLogFont.lfWeight = FW_NORMAL;

     tLogFont.lfItalic = 1;

     tLogFont.lfUnderline = 0;

     tLogFont.lfStrikeOut = 0;

     tLogFont.lfCharSet = GB2312_CHARSET;

     tLogFont.lfOutPrecision = OUT_DEFAULT_PRECIS;

     tLogFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;

     tLogFont.lfQuality = DEFAULT_QUALITY;

     tLogFont.lfPitchAndFamily = DEFAULT_PITCH | FF_SWISS;

     strcpy( tLogFont.lfFaceName, _T("宋体") );

 

    

     RECT rect;

     CFont rFont;

     CFont* pOldFont;

     rect.left = 10;

     rect.right = 10;

     rect.top = 10;

     rect.bottom = 10;

 

     pDC = GetDC( );

     rFont.CreateFontIndirect( &tLogFont );

     pOldFont = pDC->SelectObject( &rFont );

 

     //测试字符串

     CString sTestStr = "asdfas基本面有dasdf在在有有dffds有有有有有有sdfasdfa城  在 sdf~!@#$%^&*()_+sdfasdfasdf";

     //此处nHeight为字符串高度,rect为测试后字符串显示所站区域大小

     int nHeight = pDC->DrawText( sTestStr,&rect, DT_SINGLELINE|DT_LEFT| DT_CALCRECT);

     pDC->DrawText( sTestStr,&rect, DT_SINGLELINE|DT_LEFT);

     //在区域最后画一条竖线来测试结果

     pDC->MoveTo( rect.right, rect.top );

     pDC->LineTo( rect.right, rect.bottom );

     //释放资源

     pDC->SelectObject( pOldFont );

     rFont.DeleteObject( );

     ReleaseDC( pDC );

}

你可能感兴趣的:(字符串)