Saturday, 13 December 2014

Apply a Text Label with Optional background on to a Graphics Object (System.Drawing)

The following code allows you to apply to text label on to a Graphics object in C#. The background is optional but very useful if you want to set a properly aligned background color for your text label. Note: I use a lot of using statements so that anything implementing IDisposable is disposed of properly.

Usage:
Code Snippet
  1. using (Bitmap b = new Bitmap("FULL PATH TO YOUR IMAGE"))
  2. {
  3.     using (Graphics g = Graphics.FromImage(b))
  4.     {
  5.         using (Font fontText = new Font(new FontFamily("Verdana"), 14, FontStyle.Bold)) // Verdana 14em Bold
  6.         {
  7.             using (Brush fontTextBrush = new SolidBrush(Color.White)) // White Text Color
  8.             {
  9.                 PointF fontTextPoint = new PointF(5, 5); // Write the text at position (5,5)
  10.                 string textLabel = "Hello From TutorialGenius.com!";
  11.                
  12.                 // Example - Black background
  13.                 this.ApplyText(g, textLabel, fontText, fontTextBrush, fontTextPoint, Color.Black);
  14.                
  15.                 // Example - No background
  16.                 this.ApplyText(g, textLabel, fontText, fontTextBrush, fontTextPoint);
  17.             }
  18.         }
  19.     }
  20. }
End of Code Snippet


Code Snippet
  1. // Applies a text layer with optional background onto a Graphics object
  2. private void ApplyText(Graphics g, string text, Font font, Brush brush, PointF? point = null, Color? backgroundColor = null)
  3. {
  4.     if (point == null) point = new PointF(0, 0);
  5.  
  6.     // First - Apply optional background color
  7.     if (backgroundColor.HasValue)
  8.     {
  9.         SizeF fontTextSize = g.MeasureString(text, font);
  10.         using (Brush fillBrush = new SolidBrush(Color.Black))
  11.             g.FillRectangle(fillBrush, point.Value.X, point.Value.Y, fontTextSize.Width, fontTextSize.Height);
  12.     }
  13.  
  14.     // Second - Draw string on graphics object
  15.     g.DrawString(text, font, brush, point.Value);
  16. }
End of Code Snippet

No comments: