zoukankan      html  css  js  c++  java
  • c#长字符串显示省略号

            // 功能:将输入的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;
                    }
                }
            }

  • 相关阅读:
    Web Control 开发系列(三) 解析IPostBackEventHandler和WebForm的事件机制
    Web Control 开发系列(一) 页面的生命周期
    异步导入滚动条
    前端复习之HTML5
    前端复习之jQuery大全
    前端复习之JavaScript(ECMAScript5)
    前端复习之DOM、BOM
    前端复习之Ajax,忘完了
    前端复习之css
    前端基础复习之HTML
  • 原文地址:https://www.cnblogs.com/youyou/p/653865.html
Copyright © 2011-2022 走看看