How to

draw centered text

Published: 21. January 2009 | Updated: 21. January 2009
License: Microsoft Public License (MS-PL)
Categories: GDI
Tags: C# GDI Text Winforms
Was this snippet helpful for you? YESYES / NONO

Import namespace

using System.Drawing;

Code

string text = "My text";

// create graphics, font and brush
Graphics graphics = this.CreateGraphics();
Font font = new Font("Verdana", 15);
SolidBrush brush = new SolidBrush(Color.Red);

// specifying string format - centre text
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;

// draw string
graphics.DrawString(text, font, brush, (RectangleF)this.DisplayRectangle, format);

// dispose
font.Dispose();
brush.Dispose();
graphics.Dispose();
Send us feedback about this snippet »



Related Snippets: