Window Mobile 精确获取文本绘制区域大小

针对.NET CF中Drawing的MeasureString方法存在的局限性,本文介绍了一种改进的文字绘制区域测量方法。通过封装DrawText方法并利用GDI+ API,实现指定区域内文字绘制尺寸的精确计算,适用于不同字体和样式。

在.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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值