BLOG.CSHARPHELPER.COM: Use the StringFormat class's line trimming values in C#
Use the StringFormat class's line trimming values in C#
The StringFormat class controls how a piece of text is drawn by a Graphics object's DrawString method. For example, the StringFormat object can make the text appear aligned on the left, right, top, bottom, or center. It can also make the text appear inside a specified Rectangle.
The StringFormat class's Trimming property determines what DrawString does if the string doesn't fit inside the Rectangle.
The following list describes the effects of each of the possible Trimming values.
None: No trimming. (Seems to have the same effect as Word.)
Character: Stops after drawing the last character that will fit.
Word: Stops after drawing the last word that will fit.
EllipsisCharacter: Draws as many characters as possible and then ends the string with an ellipsis.
EllipsisWord: Draws as many words as possible and then ends the string with an ellipsis.
EllipsisPath: Draws the beginning of the string, an ellipsis, and then the end of the string.
The EllipsisPath value is useful when it's useful to see the beginning and ending of the string. For example, if you are showing a file's full path and name, then this value lets you see the beginning of the path so you know in what part of the system the file lies and the end of the path so you can see the file's name.
The program uses the following code to draw 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 = 5; StringTrimming[] values = (StringTrimming[])Enum.GetValues(typeof(StringTrimming)); int height = (ClientSize.Height - (values.Length + 1) * margin) / values.Length; int width = ClientSize.Width - 2 * margin;
using (Font font = new Font("Times New Roman", 16)) { using (StringFormat string_format = new StringFormat()) { int y = margin; foreach (StringTrimming trimmming in values) { Rectangle rect = new Rectangle(margin, y, width, height); e.Graphics.DrawRectangle(Pens.Black, rect); string_format.Trimming = trimmming; e.Graphics.DrawString(trimmming.ToString() + ": " + quote, font, Brushes.Blue, rect, string_format);
y += height + margin; } } } }
The key pieces of this code start when the program creates the StringFormat object. Notice that the code includes a using statement to automatically call the StrfingFormat's Dispose method.
The code loops through the StringTrimming values returned by Enum.GetValues. For each, it sets the StringFormat object's Trimming property and draws the string. It also draws the formatting rectangle so you can see where the text is limited.
(The full Mark Twain quote is "The trouble ain't that there is too many fools, but that the lightning ain't distributed right.")
Comments