确定基于文本和字体大小的WinForms / C#数量标签尺寸 [英] Determine Label Size based upon amount of text and font size in Winforms/C#

查看:236
本文介绍了确定基于文本和字体大小的WinForms / C#数量标签尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更好的办法处理这一问题。我想调整的标签(垂直),以容纳一定量的文本。我的标签具有固定的宽度(大约60个字符宽之前必须包),大约495像素。字体也是固定大小(12points AFAIK),但该文本是没有的。

我想要做的就是增加标签的高度时,有一个换行或文本必须换行;这个想法是,该文本是在标签完全可见。将AutoSize不起作用,因为它会增加宽度,没有高度。

当然,我可以指望换行的数量,并添加:换行* lineHeight是,然后-given,我设法把每行60个字符,只划分字符的数量,并根据需要添加尽可能多的lineHeight是像素

我在想,如果有一个更专业的方式来做到这一点。是我的做法太跛脚?

在此先感谢。

解决方案

如何 Graphics.MeasureString ,与接受一个字符串,字体过载,和最大宽度?这会返​​回一个的SizeF ,这样你就可以道道通断身高

 使用(图形G =的createGraphics()){
            的SizeF大小= g.MeasureString(文字,lbl.​​Font,495);
            lbl.Height =(INT)Math.Ceiling(size.Height);
            lbl.Text =文本;
        }
 

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 (about 60 chars wide before it must wrap), about 495 pixels. The font is also a fixed size (12points afaik), but the text is not.

What I want to do is increase the Label Height when there's a "NewLine" or the text must wrap; the idea is that the text is fully visible in the label. The AutoSize doesn't work because it will grow in width, not in height.

Of course I could count the number of NewLines and add: Newlines * LineHeight, and then -given that I manage to put 60 chars per line, just divide the number of chars and add as many LineHeight pixels as needed.

I was wondering if there was a more professional way to do it. Is my approach too "lame" ?

Thanks in advance.

解决方案

How about Graphics.MeasureString, with the overload that accepts a string, the font, and the max width? This returns a SizeF, so you can round round-off the Height.

        using(Graphics g = CreateGraphics()) {
            SizeF size = g.MeasureString(text, lbl.Font, 495);
            lbl.Height = (int) Math.Ceiling(size.Height);
            lbl.Text = text;
        }

这篇关于确定基于文本和字体大小的WinForms / C#数量标签尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆