views:

73

answers:

2

Hello, 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.

A: 

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.

Ed Guiness
No.2 point is not an option as that would make the control having rectangles with different font sizes. I guess I need to look on No.1 and see if tit returns the perfect rectangle to draw a string in it.
Mohit
@Mohit - don't confuse the height of your drawn string with the height of the image containing that drawn string. I'm assuming you want to make the string as wide as possible up to 100px, without changing the aspect ratio (width/height) of the STRING (the image is fixed as you've emphasised).
Ed Guiness
Hello Ed. Sorry for the late reply. I need to make the rectangle's width constant as 100px and adjust height to display the complete string inside it.I used TextRenderer.MeasureText but still not getting the desired result. I am acutally developing a control that displays some strings in coloured rectangles. So, the string need to display in full.
Mohit
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.SOLVED....
Mohit
A: 

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/

Mohit