Use the StringFormat class's string format flags in C#

The example Use the StringFormat class's line trimming values in C# shows how to determine what the DrawString method does when some text's last line doesn't fit horizontally in a formatting region. This example shows how to use the StringFormat object's FormatFlags property to determine what happens if the last line won't fit vertically.

The following list describes each of the relevant settings.

  • 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 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 ...";
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's Dispose method.

The code loops through the values placed in the flags array by the code (other FormatFlags values are not included because they don't deal with line clipping). For each value, the code draws a formatting rectangle and then draws text in it.

  

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.