Word wrapping on DrawString method

M

Marcos Cruz Arjona

Hi,

In order to draw a formatted text inside a rectangle on a custom
control, I use Graphics.DrawString(string, Font, Brush, RectangleF) method.
However, when the text is too large for the specified rectangle, the method
word wraps the text, instead of just clipping it on a single line.
Therefore, do I have to use DrawText unmanaged function or is there a
workaround?


Best regards,

M a r c o s
 
A

Alex Feinman [MVP]

Try setting the RectangleF parameter to be the height of the single line of
text. To do this, use MeasureString with a string short enough not to wrap
 
M

Marcos Cruz Arjona

Alex,

I had already tried this and it doesn't works. DrawString always cuts
words (separated by spaces) that doesn't fit in the specified rectangle
width, in spite of rectangle height.

Thanks,

M a r c o s
 
T

Tim Wilson

One way to do this is to define the clipping region for the Graphics object
and then use the DrawString overload that takes X and Y coordinates [public
void DrawString(string, Font, Brush, float, float)].

<Basic Idea>
e.Graphics.Clip = new Region(new Rectangle(0, 0, 50, 20));
e.Graphics.DrawString("This is a pretty long string of text!", this.Font,
new SolidBrush(Color.Black), 0, 0);
e.Graphics.ResetClip();
</Basic Idea>
 
M

Marcos Cruz Arjona

Tim,

I'll try this!

Thanks,

M a r c o s

Tim Wilson said:
One way to do this is to define the clipping region for the Graphics object
and then use the DrawString overload that takes X and Y coordinates [public
void DrawString(string, Font, Brush, float, float)].

<Basic Idea>
e.Graphics.Clip = new Region(new Rectangle(0, 0, 50, 20));
e.Graphics.DrawString("This is a pretty long string of text!", this.Font,
new SolidBrush(Color.Black), 0, 0);
e.Graphics.ResetClip();
</Basic Idea>

--
Tim Wilson
.Net Compact Framework MVP
{cf147fdf-893d-4a88-b258-22f68a3dbc6a}
Marcos Cruz Arjona said:
Alex,

I had already tried this and it doesn't works. DrawString always cuts
words (separated by spaces) that doesn't fit in the specified rectangle
width, in spite of rectangle height.

Thanks,

M a r c o s

"Alex Feinman [MVP]" <[email protected]> escribió en el mensaje
line
of
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top