C#在Winform下文字高度计算方法

首先明确一点,Winform下的所有UI绘制都是基于GDI+的,所以网上能找到的关于文字高宽计算的都采用以下方式来进行

string content = "目标文本";
Graphics g = this.CreateGraphics(); //this是指所有control派生出来的类,这里是个form
SizeF size = g.MeasureString(content, new Font(fontName, fontHeight, FontStyle.Regular));

但通过MeasureString计算出来的长度随着字数的增加,误差会越来越大,具体原因有兴趣研究的可以看一下freetype这个开源库对文字的处理过程。

同时,这种测定是单行文字,计算高度的时候需要除行宽来计算行数,再设定行高,一来二去误差就不可避免了。

如何解决这个误差,看你需要的场景,所有的control都有一个公共方法,就是获取这个控件的位图信息。那么思路就很明确了。在你需要排版的控件内放置这些文字,把控件的高度足够高,然后设置边框为None,这么做是为了避免图像处理时的干扰,最后通过对位图操作,裁减掉位图下放的空白区域,得到的新位图就是你要获取的信息,位图高度就是真实高度。

下边的例子是基于TextBox多行模式下获取文本的高度。返回值y就是最终高度坐标。

        ///获取控件的位图
        private Bitmap GetBitmap(Control c)
        {
            Bitmap memmap = new Bitmap(c.Width, c.Height);
            c.DrawToBitmap(memmap, new Rectangle(new Point(0, 0), c.Size));
            return memmap;
        }


        ///传入位图获取真实高度
        private int ResizeBitmap(Bitmap bmp)
        {
            int wide = bmp.Width;

            int height = bmp.Height;

            int start = -1,end = -1;
            int count = 0;
            bool isblank = true;
            int y = 0;

            for (; y < height; y++)
            {
                //isblank = true;
                for (int x = 0; x < wide; x++)
                {
                    Color srcColor = bmp.GetPixel(x, y);
                    if (srcColor.R != 255 || srcColor.G != 255 || srcColor.B != 255)
                    {
                        isblank = false;
                        if (start == -1)
                            start = y;
                        break;
                    }
                    else
                        isblank = true;

                }
                if (start >= 0)
                {
                    if (isblank)
                    {
                        count++;
                    }
                    else
                        count = 0;
                }
                if (count == 1)
                    end = y;
                if (count > 20)
                {
                    //Console.WriteLine(y.ToString());
                    return end;
                }
            }
            return y;

        }

 

你可能感兴趣的:(算法,Win32)