Determine Label Size based upon amount of text and font size in Winforms/C#

前端 未结 11 1744
半阙折子戏
半阙折子戏 2020-11-30 01:27

I\'d like to know if there\'s a better approach to this problem. I want to resize a label (vertically) to accomodate certain amount of text. My label has a fixed width (abou

11条回答
  •  庸人自扰
    2020-11-30 02:07

    In some cases where you must use compact framework, which does not have any override methods for MeasureString(), you might consider calculating the height by yourself.

    private int YukseklikAyarla(string p, Font font, int maxWidth)
        {
            int iHeight = 0;
            using (Graphics g = CreateGraphics())
            {
                var sizes = g.MeasureString(p, font); // THE ONLY METHOD WE ARE ALLOWED TO USE
                iHeight = (int)Math.Round(sizes.Height);
                var multiplier = (int)Math.Round((double)sizes.Width) / maxWidth; // DIVIDING THE TEXT WIDTH TO SEE HOW MANY LINES IT CAN HAS
                if (multiplier > 0)
                {
                    iHeight = (int)(iHeight * (multiplier + 1)); // WE ADD 1 HERE BECAUSE THE TEXT ALREADY HAS A LINE
                }
            }
            return iHeight;
        }
    

提交回复
热议问题