c# 文本超长截断

根据控件大小进行截断

  private void SetStringTruncat(Static.LabelEx lbl)
        {
            string oldStr = lbl.Text;
            if (string.IsNullOrEmpty(oldStr))
                return;

            Graphics g = lbl.CreateGraphics();
            string strNewStr = string.Empty;            
            for (int i = 0; i < oldStr.Length; i++)
            {
                strNewStr = oldStr.Substring(0, oldStr.Length - i) + "";
                SizeF sizeF = g.MeasureString(strNewStr, lbl.Font, 1000, StringFormat.GenericTypographic);
                if (sizeF.Width <= lbl.MaximumSize.Width - 20)
                {
                    break;
                }
            }
            g.Dispose();
            if (strNewStr == oldStr + "")
                strNewStr = oldStr;
            lbl.Text = strNewStr;
        }

 

posted @ 2018-10-31 10:07  冰封一夏  阅读(784)  评论(0编辑  收藏  举报
HZHControls控件库官网:https://www.hzhcontrols.cn