Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graphics DrawString() clipping text off while rectangle still have more room

Tags:

c#

graphics

I have something like this:

There are 3 rectangles of the same size width 60px each.

...
var font = new Font("Arial", 9, FontStyle.Bold);
var format = new StringFormat() {FormatFlags = StringFormatFlags.LineLimit} 
...
g.DrawString(content, font, brush, rect, format);

enter image description here

(Note: I put borders around text and a red line cutting before 'A's to make it easy to see the boundaries)

I realise the DrawString() is trimming off my 'M' of 10 & 11 AM. However, if you examine how the red line cuts off the 'A's, you see the first row of 'A' from 9:00 AM seats a couple pixels further away than the 2 A's below it, but AM didn't get trimmed off.

That means, actually the rectangles DO still have enough space to fit the 'M' in, we can tell from the red line, but DrawString() choose to clip it off instead, why? How to fix it?

like image 239
Tom Avatar asked Oct 25 '25 21:10

Tom


1 Answers

Hope, setting format = new StringFormat(StringFormatFlags.LineLimit | StringFormatFlags.NoWrap, 1003) { Trimming = StringTrimming.None })

RectangleF rec = new RectangleF();
rec.X = 100;
rec.Y= 100;
rec.Width = 100;
rec.Height = 20;
e.Graphics.DrawRectangles(Pens.Black, new RectangleF[] { rec });
e.Graphics.DrawString("12345678901234", new Font("Arial", 9, FontStyle.Bold), Brushes.Red, rec, 
new StringFormat(StringFormatFlags.LineLimit | StringFormatFlags.NoWrap, 1003) { Trimming = StringTrimming.None });

Here's the output with new StringFormat(StringFormatFlags.LineLimit, 1003) Incorrect output

and here's the correct output with new StringFormat(StringFormatFlags.LineLimit | StringFormatFlags.NoWrap, 1003) { Trimming = StringTrimming.None }) enter image description here

will make a difference in your case.

like image 69
Rohit Prakash Avatar answered Oct 27 '25 12:10

Rohit Prakash