C# 获取固定像素字符串

View Code
 System.Windows.Forms.TextBox tb = new System.Windows.Forms.TextBox();
                System.Drawing.Font stringFont = new System.Drawing.Font("Microsoft YaHei", 18);
                tb.Font = stringFont;
                string strName = stringFormat(tb, singleUCBtn.SingleUCName, 180);    
     /// <summary>
        /// 根据像素长度限制返回字符串
        /// </summary>
        /// <param name="txtb"></param>
        /// <param name="w"></param>
        /// <returns></returns>
        public static string stringFormat(System.Windows.Forms.TextBox txtb, string strInfo, int lengh)
        {
            bool b=false;
            int length = strInfo.Length;
            string temp="";
            for (int i = 1; i <= length; i++)
            {
                if (GetMaxTextLength(tb, temp) > lengh)
                {
                    b = true;
                    break;
                }
                temp=strInfo.Substring(0,i);           
            }
            //if (b)
                //temp = temp + "...";

            return (temp);
        }
View Code
      /// <summary>
        /// 计算字符串的像素长度
        /// </summary>
        /// <returns>字符串长度</returns>
        private static int GetMaxTextLength(System.Windows.Forms.TextBox tb, string strMax)
        {
            int iTextLength = (int)tb.CreateGraphics().MeasureString(strMax, tb.Font).Width;
            return iTextLength;
        } 

 

posted @ 2012-11-21 21:38  风雨摇摆  阅读(289)  评论(0)    收藏  举报