GDI 与 GDIPlus 获取文字宽度和高度的方法

GDI 与 GDIPlus 获取文字宽度的方法 
/// GDI获得字体宽度的方法
CClientDC dc(this);  
CFont font;  
//Requested font height in tenths of a point.
//For instance, pass 120 to request a 12-point font.)
//由上面解释可知,120这个参数是取其1/10为作为字体大小,
//不过实际中计算中文时,发现比例为11:1,这个有待进一步研究
font.CreatePointFont(120, _TEXT("Arial"));
dc.SelectObject(font);  
CSize size= dc.GetTextExtent(_TEXT("字体大小"));/// 这是以Point(点)为单位的计算方法
 
int nDPIx = dc.GetDeviceCaps(LOGPIXELSX);/// X坐标每英寸的点数 Dot per Inch
int nDPIy = dc.GetDeviceCaps(LOGPIXELSY);/// Y坐标每英寸的点数 Dot per Inch
/// Point(点) 转化为 Pixel(像素)
int textWidth = dc.GetTextExtent(_TEXT("字体大小")).cx * 72 / nDPIx;
int textHeight = dc.GetTextExtent((_TEXT("字体大小")).cy * 72 / nDPIy; 
 
/// GDIPlus获得字体宽度的方法一
Gdiplus::Font grFont(_TEXT("Arial"), 12);
StringFormat stringformat(StringAlignmentNear);
LPCTSTR lpStr = _TEXT("2010Text测试文本");
// 接收字体的显示区域,如宽高
RectF stringRect;   
RectF layoutRect(0, 0, 600, 100);
//graphics.SetTextRenderingHint(Gdiplus::TextRenderingHintClearTypeGridFit );
//获得字体高度与宽度stringRect
graphics.MeasureString(lpStr, (int)_tcslen(lpStr), &grFont, layoutRect, &stringformat, &stringRect);
实际应用时,我们发现,如果是非中文字符串,如字母和数字,用MeasureString测量出来的宽度基本正确,
可一旦这个字符串中存在中文,用MeasureString测量出来的结果就有偏差了。


现改用GraphicsPath的边界来处理,测试结果比较精确。
/// GDIPlus获得字体宽度的方法二
SizeF GetTextBounds(const Font& font,const StringFormat& strFormat,const CString& szText)
{
    GraphicsPath graphicsPathObj;
    FontFamily fontfamily;
    font.GetFamily(&fontfamily);
    graphicsPathObj.AddString(szText,-1,&fontfamily,font.GetStyle(),font.GetSize(),\
                              PointF(0,0),&strFormat);
    RectF rcBound;
    /// 获取边界范围
    graphicsPathObj.GetBounds(&rcBound);
    /// 返回文本的宽高
    return SizeF(rcBound.Width,rcBound.Height);
}
case WM_PAINT:
		{
		hdc = BeginPaint(hWnd, &ps);
		Graphics graphics(hdc);
		Font font(L"微软雅黑", 12);
		RectF layout(0, 0, 400, 500);
		StringFormat stringFormat;
		SizeF size;
		SolidBrush brush(Color(255, 255, 0, 255));
		SizeF strSize;	//GDI+ 字体大小
		//如果实际字体长度和高度大于这个值,返回的宽度和高度将被设置成layoutSize的长和宽
		//所以为了得到实际的字体高度和宽度应该将layout设置成足够大
		SizeF layoutSize(10, 10);
		graphics.MeasureString(szString, -1, &font, layoutSize, NULL, &strSize);
		graphics.DrawString(szString, -1, &font, PointF(400, 300), &stringFormat, &brush);
		EndPaint(hWnd, &ps);
		}
		break;





来源:http://blog.sina.com.cn/s/blog_4b44e1c00100kw1t.html

你可能感兴趣的:(Windows应用层编程)