心有

知其所以然,方可大道至简。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

        // 功能:将输入的str字符串格式化成width宽度能输出的字符串,如果字符串太长,则格式化为"start...end"格式
        // str -- 要格式化的字符串
        // width -- 最大的输出长度
        // prefixCount -- 前缀字符个数
        public string StringFormat(Graphics g, Font ft, string str, float width, int prefixCount)
        {
            SizeF sf;

            sf = g.MeasureString(str, ft);
            if(sf.Width <= width)
            {
                return str;
            }
            else
            {
                string result = "";
                string strTemp;
                SizeF sfTemp = new SizeF(0, 0);
                float wdTemp;
                int i;
                bool flag = false;

                if (prefixCount < str.Length)
                {
                    result = str.Substring(0, prefixCount) + "...";
                    sfTemp = g.MeasureString(result, ft);
                    flag = true;
                }

                if (flag && sfTemp.Width < width)
                {
                    strTemp = "";
                    wdTemp = width - sfTemp.Width;
                    for (i = str.Length - 1; i > 0; i--)
                    {
                        strTemp = str[i] + strTemp;
                        sfTemp = g.MeasureString(strTemp, ft);
                        if (sfTemp.Width >= wdTemp)
                        {
                            i++;
                            break;
                        }
                    }

                    result += str.Substring(i);

                    return result;
                }
                else
                {
                    strTemp = "";
                    sfTemp = g.MeasureString("...", ft);
                    wdTemp = width - sfTemp.Width;
                    for (i = 0; i < str.Length; i++)
                    {
                        strTemp += str[i];
                        sfTemp = g.MeasureString(strTemp, ft);
                        if (sfTemp.Width >= wdTemp)
                        {
                            i--;
                            break;
                        }
                    }

                    result = str.Substring(0, i) + "...";

                    return result;
                }
            }
        }

posted on 2007-02-22 21:40  心有  阅读(2256)  评论(0编辑  收藏  举报