zoukankan      html  css  js  c++  java
  • 计算纯文本情况下RichTextBox实际高度的正确方法(.NET)

    2016-07-17重大更新

              其实有更好、更系统的方法,也是最近才发现的,分享给大家!!

         

            /// <summary>
            /// 
            /// </summary>
            /// <param name="width"></param>
            public MyControl(int width)
                : this()
            {
                this.Width = width;
                this.richtxtContent.Width = this.Width - 30;
    
                this.richtxtContent.WordWrap = true;
                this.richtxtContent.ScrollBars = RichTextBoxScrollBars.None;
                this.richtxtContent.ContentsResized += new ContentsResizedEventHandler(richtxtContent_ContentsResized);
            }
    
            /// <summary>
            /// 
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void richtxtContent_ContentsResized(object sender, ContentsResizedEventArgs e)
            {
                RichTextBox rtb = sender as RichTextBox;
                if (rtb != null)
                {
                    rtb.Size = e.NewRectangle.Size;
                }
            }
    

    -------------------------------------------------------------------------------------

      在WinForm开发中,经常会用到RichTextBox控件,也经常会碰到需要自动调节RichTextBox高度的场景。本人鉴于这种情况,查阅了一些资料,确定了正确的方法。

      基本思路就是获取RichTextBox中一行文本的实际高度。

      1、首先计算出RichTextBox中文本的行数
         
            int rowCount = this.txtBox.GetLineFromCharIndex(this.txtBox.SelectionStart) + 1;
     
      2、然后计算一行文本的高度
     
        System.Drawing.Point ptLine1  //第一行第一个字节的坐标
            = this.txtBox.GetPositionFromCharIndex(this.txtBox.GetFirstCharIndexFromLine(0));
        System.Drawing.Point ptLine2  //第二行第一个字节的坐标
            = this.txtBox.GetPositionFromCharIndex(this.txtBox.GetFirstCharIndexFromLine(1)); 
       
        其中GetFirstCharIndexFromLine是从指定行获取第一个字节的序号(index),GetPositionFromCharIndex则是获取指定序号(index)字节的坐标。
     
            注:为了取得正确的ptLine2,一定要保证RichTextBox文本至少有二行。
     
      3、然后,计算RichText的行高度
           
        int textLineHeight = ptLine2.Y - ptLine1.Y;
     
      4、然后,计算RichTextBox的高度
     
        this.txtBox.Height = rowCount * txtLineHeight
                                   + this.txtBox.Margin.Top 
                                   + this.txtBox.Margin.Bottom;
     
        其中,this.txtBox.Margin.Top为顶部空白,this.txtBox.Margin.Bottom为底部空白。
     
      5、然后就木有然后了~
         
  • 相关阅读:
    PostMan-NewMan运行参数
    shell脚本学习简单记录笔记
    android开发okhttp-4.9.1源码大致流程解读
    android开发获取键盘高度以及判断键盘是否显示(兼容分屏模式)
    Android开发The style on this component requires your app theme to be Theme.AppCompat (or a descendant)的解决方法
    Linux开发Ubuntu安装man手册
    Android开发源码解读四大组件源码解读简单梳理
    Android开发涉及到的AMS类和ActivityThread类源码解读
    Android开发为什么主线程可以一直运行而不会退出来
    前端CryptoJS加密、后端解密代码实现参考
  • 原文地址:https://www.cnblogs.com/junier/p/3211029.html
Copyright © 2011-2022 走看看