确定基于文本和字体大小的WinForms / C#数量标签尺寸

编程入门 行业动态 更新时间:2024-10-27 04:29:00
本文介绍了确定基于文本和字体大小的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#数量标签尺寸

本文发布于:2023-10-08 08:52:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1472119.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字体大小   尺寸   数量   标签   文本和

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!