大力水手的Blog

大力水手语录

导航

[导入]高度自动变化的Label

 

 /// <summary>
 /// AutoLabel 在宽度一定的情况下,
 /// 高度随内容的变化而变化
 /// 作者:周鼎汉
 /// 日期:2007.05.25
 /// QQ:16115636
 /// Email:dinghan.zhou@126.com
 /// CopyRight By 周鼎汉
 /// </summary>
 
 public class AutoLabel:System.Windows.Forms.Label
 {
  public AutoLabel()
  {
   
  }
  protected override void OnPaint(PaintEventArgs e)
  {
   //取得事件参数中的Graphics
   Graphics g=e.Graphics;
   //当前控件的高度为行数×字体的高度
   this.Height=GetStringLines(this.Text,g)*this.Font.Height;
   base.OnPaint (e);
  }
  /// <summary>
  /// 得到给定的多行字符串在Label上共
  /// 需要显示的行数。
  /// </summary>
  /// <param name="s">给定的字符串</param>
  /// <param name="g">Graphics</param>
  /// <returns>行数</returns>
  private int GetStringLines(string s,Graphics g)
  {
   //使用StringReader按行读取内容
   StringReader sr=new StringReader(s);
   //行数计数器
   int count=0;
   
   while(true)
   {
    string temp=sr.ReadLine();
    //直到读取完成,返回行数
    if(temp==null)
    {
     return count;
    }
    //计算当前读取的字符串的行数。
    count+=GetSingleStringLines(temp,g);
   }

  }

  /// <summary>
  /// 得到一个单行字符串在给定宽度的标签上的行数。
  /// </summary>
  /// <param name="s">单行字符串</param>
  /// <param name="g">当前的Graphics</param>
  /// <returns>字符串s显示的行数</returns>
  private int GetSingleStringLines(string s,Graphics g)
  {
   //取得当前标签的字体
   Font font=this.Font;
   //当前标签的宽度
   int width=this.Width;
   //循环变量
   int i=0;
   //截取字符串的起始位置
   int start=0;
   //行数
   int lines=0;
   while(true)
   {
    //临时字符串
    string temp;
    //如果起始位置的值+截取的长度小于或等于s的长度
    //那么应该继续截取
    //否则表示这个字符串已经处理完成(并且这个字符串正好是每行都整行占满).
    //返回行数
    if((start+i)<=s.Length)
    {
     temp=s.Substring(start,i);
    }
    else
    {
     return ++lines;
    }
    //测试截取后的字符串的长度是否大于标签的宽度
    //如果小于,那么需要下一个字符填充到截取字符串中,
    //继续测量大小

    if(g.MeasureString(temp,font).Width<width)
    {
     i++;
    }
    else
    {
     //行数加1
     lines++;
     //改变截取的起始位置,因为当前的截取
     //已经超过了宽度,所以减1
     start+=(--i);
     //将开始截取的长度设置为0
     i=0;
    }
   }
  }

 }


文章来源:http://blog.sina.com.cn/s/blog_49458c27010008b3.html

posted on 2008-05-01 09:07  jack.zhou  阅读(183)  评论(0编辑  收藏  举报