The text API described in this topic is out of date. If you want to learn about text API represented by the new drawing engine in Graphics Mill, read the Drawing Text article.
When displaying text you may need to be sure that it will be generated inside a rectangle. For example, this is necessary when you draw text on a button or in a box. If the text string is longer than this rectangle's width the lines should be automatically wrapped or clipped.
Graphics Mill provides all these features and allows writing multiline text using the Graphics class in two ways. The first way includes the Graphics.DrawText method, which is suitable for drawing text in a single style. All the font and color settings are defined by the Font and SolidBrush class properties and are the same for the whole text. To get the dimensions of a rectangle which is drawn by this method and occupied with multiline text Graphics Mill provides the Graphics.MeasureText method. The second way to draw multiline text is conducted by using the Graphics.DrawFormattedText method. The main difference between these two methods is the possibility to display multi-style text. It means that the Graphics.DrawFormattedText method supports text with portions of different justification, font and color settings. The size of the text drawn by this method can be measured with the Graphics.MeasureFormattedText method.
The Graphics.DrawText method accepts the following arguments:
The Graphics.DrawText method supports newline and tabulation characters
such as \n
and \t
in C#, respectively. It makes the characters after the newline symbol
display in a new line and replaces the tabulation character with the specified number of whitespaces.
The following code example draws the text box below:
using (var bitmap = new Bitmap(300, 250, PixelFormat.Format24bppRgb, RgbColor.White))
using (var graphics = bitmap.GetGraphics())
{
//define font and color settings
var font = new Font("Arial", 20);
font.HorizontalAlignment = HorizontalAlignment.Center;
var brush = new SolidBrush(RgbColor.Black);
string text = "How many cans can a canner can if a canner can can cans?\n" +
"A canner can can as many cans as a canner can if a canner can can cans.";
var rect = new System.Drawing.Rectangle(50, 50, 200, 150);
//Draw multiline text with rectangle object
graphics.DrawText(text, font, brush, rect, true, 3);
bitmap.Save(@"Images\Output\text.png");
}
This method is quite similar to Graphics.DrawText and uses the same parameters. However, the text string you want to draw must be marked up with XML-like tags. The marks specify text rendering settings for each portion of the text. The XML specification is completely described in the Formatted Text article.