Sarien
Sarien

Reputation: 6982

How do I use DrawString without trimming?

I find the way the DrawString function cuts off entire characters or words to be counterintuitive. Showing parts of the text clearly conveys that something is missing.

Here are some examples:

StringTrimming.None: enter image description here

StringTrimming.Character: enter image description here

What I want: enter image description here (GIMP mockup)

Is StringTrimming.None the same as StringTrimming.Character? They seem to behave exactly alike in my case. Is there something I could have overlooked or is this a known "feature"?

According to the docs StringTrimming.None "Specifies no trimming."

This site with examples created with Java even show "None" to trim more characters than "Character".

Are there other tricks to get this effect?

Note: I do not want to display "…" or similar. I find this to be a waste of space but that is probably a discussion for UX.

Upvotes: 19

Views: 6383

Answers (2)

Michael Liu
Michael Liu

Reputation: 55419

It's possible that the text appears to be trimmed because it's actually wrapping invisibly onto the next line. In the call to Graphics.DrawString, disable wrapping by passing a StringFormat object whose FormatFlags property is set to NoWrap:

StringFormat format =
    new StringFormat
    {
        FormatFlags = StringFormatFlags.NoWrap,
        Trimming = StringTrimming.None
    };
g.DrawString(s, font, brush, rect, format);

Upvotes: 15

Rotem
Rotem

Reputation: 21927

As a workaround, you can give the DrawString method a bigger RectangleF than you really want, and set the clipping region of your Graphics object to the actual RectangleF you want to draw the string in.

RectangleF rect = new RectangleF(10, 10, 30, 15);
e.Graphics.DrawRectangle(Pens.Red, Rectangle.Truncate(rect));

RectangleF fakeRect = new RectangleF(rect.Location, new SizeF(short.MaxValue, short.MaxValue));

Region r = e.Graphics.Clip;
e.Graphics.SetClip(rect);            
e.Graphics.DrawString("1 Default", this.Font, SystemBrushes.ControlText, fakeRect);
e.Graphics.Clip = r;

Note that this code assumes you wish to anchor your text to the top left corner of the rectangle. Otherwise you should generate the fake rectangle in a method that maintains the same anchor point as your intended layout rectangle.

Upvotes: 4

Related Questions