Title: Perform line clipping in C#
The example Perform line trimming in C# shows how to determine what the DrawString method does when the last line of text doesn't fit horizontally in a formatting rectangle. This example shows how to perform line clipping when the last line won't fit vertically.
You use a StringFormat object's FormatFlags property to perform line clipping. The following list describes the available options.
- FitBlackBox: The last line is clipped to the formatting region, possibly creating characters that are chopped in half vertically.
- LineLimit: The text ends with the last line that fits completely.
- NoClip: The text ends after the last line that fits at least partially, and that line is not clipped.
- NoWrap: The text is not wrapped and is truncated after one line.
The StringFormatFlags enumeration defines some other values but they don't deal with line clipping so they aren't described here. For example, the values DirectionVertical orients the text vertically rotated 90 degrees to the right.
The following code shows how the program displays its samples.
private void Form1_Paint(object sender, PaintEventArgs e)
{
// A Mark Twain quote:
const string quote =
"The trouble ain't that there is too many fools, " +
"but that the lightning ain't distributed right.";
const int margin = 20;
StringFormatFlags[] flags =
{
StringFormatFlags.FitBlackBox,
StringFormatFlags.LineLimit,
StringFormatFlags.NoClip,
StringFormatFlags.NoWrap
};
int height =
(ClientSize.Height - (flags.Length + 1) * margin) /
flags.Length;
int width = ClientSize.Width - 2 * margin;
using (Font font = new Font("Times New Roman", 20))
{
using (StringFormat string_format = new StringFormat())
{
int y = margin;
foreach (StringFormatFlags flag in flags)
{
Rectangle rect = new Rectangle(margin, y,
width, height);
e.Graphics.DrawRectangle(Pens.Black, rect);
string_format.FormatFlags = flag;
e.Graphics.DrawString(flag.ToString() +
": " + quote, font, Brushes.Blue, rect,
string_format);
y += height + margin;
}
}
}
}
The key code starts when the program creates its StringFormat object. Notice that the code includes a using statement to automatically call the StrfingFormat object's Dispose method.
The code loops through the values placed in the flags array by the code. For each value, the code draws a formatting rectangle and then draws text in it.
Download the example to experiment with it and to see additional details.
|