Chinaunix首页 | 论坛 | 博客
  • 博客访问: 236066
  • 博文数量: 52
  • 博客积分: 1355
  • 博客等级: 中尉
  • 技术积分: 485
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-06 12:23
文章分类

全部博文(52)

文章存档

2013年(5)

2012年(16)

2011年(26)

2010年(2)

2009年(1)

2008年(2)

我的朋友

分类: C/C++

2011-08-31 15:34:07

原文:http://blog.sina.com.cn/s/blog_4b44e1c00100kw1t.html

 

/// 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);

阅读(5303) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~