开发者

Resize Rectangle based on text

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 t开发者_C百科he 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.


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.


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜