根据文本调整矩形大小

发布于 2024-09-01 12:36:03 字数 259 浏览 2 评论 0原文

我正在开发一个自定义控件,其中使用矩形来显示一些数据。现在,假设矩形的宽度和高度设置为 100。

如果我的数据量较少,那么没关系,我可以使用 DrawString 方法让它绘制。但是,有时数据较大,因此会被剪裁。

我尝试过使用 MeasureString 方法,但它没有检索到正确的值。如果必须以 100 像素宽度的矩形显示,有什么方法可以看到字符串的大小(长度和高度)。我的意思是可以增加高度,但不能增加宽度,这样我就可以使用字符串的正确高度,使其完整地显示在该矩形中。

I am working on a custom control where I am using Rectangle to show some data. Now, lets say the width and height of the rectangle is set to 100.

If I have less amount of data, then its fine, I can make it draw using DrawString method. But, sometimes Data is bigger and so it gets clipped.

I have tried using MeasureString Method, but its not retrieving the correct values. Is there any way I can see what will be the size of the string, [both length and Height], if it has to be shown in 100px width rectangle. I mean the height can be increased but not width, so that I can use the correct height of the string to make it appear in full in that rectangle.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

远昼 2024-09-08 12:36:03

听起来您有两个不同的问题需要克服

  1. 准确测量字符串。为此,请参阅 TextRenderer.MeasureText,它将为您提供预期的大小以像素为单位。

    另一种方法是绘制字符串,然后通过查找图像中不包含文本颜色的最左侧和最右侧的列来自行测量。您可以使用 GetPixel 来实现此目的。这种方法需要更多的代码,而且速度会比较慢,所以我不推荐它。

  2. 最大化绘制的字符串的大小,同时将其宽度控制在 100 以内。为此,您可以简单地测量循环中的字符串,以找到超过 100 像素的字体大小。进行猜测并从那里开始工作。

Sounds like you have two distinct problems to overcome

  1. Accurately measuring the string. For that see TextRenderer.MeasureText, which will give you the expected size in pixels.

    An alternative would be to draw your string and then measure it yourself by looking for the left and right-most columns within the image that do not contain the color of your text. You can use GetPixel for this. This method would require more code, and it would be slower, so I wouldn't recommend it.

  2. Maximising the size of your drawn string while fitting it within a width of 100. For that you can simply measure the string in a loop to find the Font size where it exceeds 100px. Take a guess and work from there.

冷情 2024-09-08 12:36:03

将矩形的高度设置为0。然后在执行MeasureString之后,我们可以找到可以放置在指定宽度的矩形内的字符串的高度。将该高度赋予要绘制的矩形,然后在其中绘制字符串。

http://www.tigraine.at /2009/01/03/gdi-drawing-string-with-word-wrap/

Set the Height of the rectangle to 0. And then after we do MeasureString, we can find the height of the string which can be placed withing that rectangle of specified width. give that height to rectangle to draw and then draw the string in it.

http://www.tigraine.at/2009/01/03/gdi-drawing-string-with-word-wrap/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文