C# 字符串换行、字符串像素高度、宽度 的结构

//字符串高度、宽,行数,及字符串本身
        public struct hhString {
            public string str; //处理后的字符串
            public int hSnumber; //共有几行(插入多少个断行符)
            public float width; //处理后的字符串宽
            public float height;//处理后的字符串高
            public hhString(string _str, float _width, float _height,Font font,Graphics g) {
                SizeF sf = g.MeasureString(_str, font);
                hSnumber = 0; //行数
                width = sf.Width;
                height = sf.Height;
                float tempWidth = 0; //循环到字符串中某个字符的宽度
                string tempStr = _str; //插入用
                int insertPoint = 0; //刚在循环中的插入点

                gotoReFor: //上一个插入点以后重新从插入点开始循环
                if (insertPoint != 0) {
                    _str = tempStr; //替换为处理后的字符串
                    sf = g.MeasureString(_str, font); //断行后字符串宽度发生变化,重新计算size
                    tempWidth = 0; //清零,因为tempWidth为上一次计算的行文字的总宽度,这里清零重新计算当前行
                }
                if (sf.Width > _width) { //字符串宽度大于单元格宽度
                    for (int i = insertPoint; i < _str.Length; i++) {
                        if (tempWidth > _width) {
                            tempStr = _str.Insert(i, "/n");
                            hSnumber ++; //行数加一行
                            insertPoint = i; //插入点变成当前插入点,下次从这个点开始循环
                            goto gotoReFor; //断行后,重新开始计算经过处理后的字符串,用于文字多于两行的多文字情况
                        }
                        tempWidth += g.MeasureString(_str[i].ToString(), font).Width + 1;
                    }
                }
                str = tempStr;
                sf = g.MeasureString(str,font);
                width = sf.Width;
                height = sf.Height;
            }
        }

 

内容摘自:http://hi.baidu.com/nethermes/blog/item/e78a88f6cdca5034730eec3e.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值