I just wanted to add (in a year) the tool that I created, because StringAlignment was not very reliable. This is very similar to the version of Neo.
The code below does an excellent job of centering the text vertically and horizontally. In addition, I wrote it with various overloads so that it would be possible to provide various parameters so that this control behaves the way I want.
Here are my overloads:
private static void DrawCenter(Label label, Graphics graphics) { DrawCenter(label.Text, label, label.Location, label.ForeColor, graphics); } private void DrawCenter(string text, Label label, Graphics graphics) { DrawCenter(text, label, label.Location, label.ForeColor, graphics); } private static void DrawCenter(string text, Label label, Point location, Graphics graphics) { DrawCenter(text, label, location, label.ForeColor, graphics); } private static void DrawCenter(string text, Label label, Point location, Color fontColor, Graphics graphics) { Rectangle rect = new Rectangle(location, label.Size); SizeF lSize = graphics.MeasureString(text, label.Font, rect.Width); PointF lPoint = new PointF(rect.X + (rect.Width - lSize.Width) / 2, rect.Y + (rect.Height - lSize.Height) / 2); graphics.DrawString(text, label.Font, new SolidBrush(fontColor), lPoint); }
To use them for the Label OnPaint event, simply change the source code in the question as follows:
private void Label_OnPaint(object sender, PaintEventArgs e) { base.OnPaint(e); Label lbl = sender as Label; if (lbl != null) { string txt = lbl.Text; e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; if (myShowShadow) {
For the Print_Document event, I have a version that will also print a field around the label if the design already has a field:
private static void DrawCenter(string text, Label label, Point location, Color fontColor, Graphics graphics) { Rectangle rect = new Rectangle(location, label.Size); SizeF lSize = graphics.MeasureString(text, label.Font, rect.Width); PointF lPoint = new PointF((rect.Width - lSize.Width) / 2, (rect.Height - lSize.Height) / 2); graphics.DrawString(text, label.Font, new SolidBrush(fontColor), lPoint); if (label.BorderStyle != BorderStyle.None) { using (Pen p = new Pen(Color.Black)) { graphics.DrawRectangle(p, rect); } } }
If you find this helpful at all, give me +1.
~ Joe