/// 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);
}
以上转自:http://blog.sina.com.cn/s/blog_4b44e1c00100kw1t.html
C#使用GraphicsPath的AddString方法示例代码如下:
此部分转自:http://www.csharpwin.com/csharpspace/9261r8948.shtml
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace advanced_drawing
{
public partial class Form14 : Form
{
public Form14()
{
InitializeComponent();
}
private void Form14_Paint(object sender, PaintEventArgs e)
{
// Create a GraphicsPath object.
GraphicsPath myPath = new GraphicsPath();
// Set up all the string parameters.
string stringText = "Sample Text";
FontFamily family = new FontFamily("Arial");
int fontStyle = (int)FontStyle.Italic;
int emSize = 26;
Point origin = new Point(20, 20);
StringFormat format = StringFormat.GenericDefault;
// Add the string to the path.
myPath.AddString(stringText,
family,
fontStyle,
emSize,
origin,
format);
//Draw the path to the screen.
e.Graphics.FillPath(Brushes.Black, myPath);
}
}
}