在.net CF中,Drawing中提供一了一个获取文字绘制区域的方法,名字为MeasureString,但在使用过程中,发现有很多问题,一是不能指定要绘制的区域,二是算出的大小不区分文本是否为粗体,于是封装了API中的DrawText方法,经测试,算出的区域十分的精确,自己封装了一个类,代码如下。
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;
namespace System.Windows.Forms.CellTable
{
public class MeasureString
{
static public Size MeasureStringEx(Graphics gr, string text, Font font, Rectangle rect)
{
RECT bounds = new RECT();
bounds.left = rect.Left;
bounds.right = rect.Right;
bounds.bottom = rect.Bottom;
bounds.right = rect.Right;
IntPtr hFont = font.ToHfont();
IntPtr hdc = gr.GetHdc();
IntPtr originalObject = SelectObject(hdc, hFont);
int flags = DT_CALCRECT | DT_WORDBREAK;
DrawText(hdc, text, text.Length, ref bounds, flags);
SelectObject(hdc, originalObject);
gr.ReleaseHdc(hdc);
return new Size(bounds.right - bounds.left, bounds.bottom - bounds.top);
}
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[DllImport("coredll")]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
[DllImport("coredll.dll")]
public static extern int DrawText(IntPtr hdc, string lpStr, int nCount, ref RECT lpRect, int wFormat);
public static int DT_CALCRECT = 0X00000400;
public static int DT_WORDBREAK = 0X00000010;
}
}
Window Mobile 精确获取文本绘制区域大小
最新推荐文章于 2025-09-13 22:12:52 发布
