Search code examples
c#.netwinformsgraphicsuser-controls

Why isn't my text right aligned when I custom draw my strings?


I'm trying to draw Right-Aligned text in a custom control, however, it seems for some reason it doesn't align to my target horizontal position and there's a difference between strings.

I can live with the fact that it doesn't exactly matches my target horizontal position, but the difference between strings is visually awful!

Any pointers?

enter image description here

The isolated code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace RightAlignTest {
    class RightControlTest : UserControl {
        public RightControlTest() {
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
        }

        public static void DrawString(Graphics g, string s, Font f, RectangleF r, Color c) {
            float locx = r.Left;
            float locy = r.Top;
            SizeF txts = g.MeasureString(s, f);
            locx = (locx + r.Width - txts.Width);
            g.DrawString(s, f, new SolidBrush(c), locx, locy);
        }

        protected override void OnPaint(PaintEventArgs e) {
            base.OnPaint(e);
            int rightTarget = Width - 20;
            Font f = new Font("Arial Unicode MS", 13f, FontStyle.Regular);
            int i = 0;
            string[] strings = { "Current Limit 1:", "Current Limit 2:", "Temperature Center 1:", "Temperature Center 2:" };
            foreach (var s in strings) {
                Rectangle r1 = new Rectangle(0, 30 * i++, rightTarget, Height);
                DrawString(e.Graphics, s, f, r1, Color.Black);
            }
            e.Graphics.DrawLine(new Pen(new SolidBrush(Color.Blue)), rightTarget, 0, rightTarget, Height);
        }
    }
    public partial class Form1 : Form {
        public Form1() {
            RightControlTest t = new RightControlTest();
            t.Dock = DockStyle.Fill;
            Controls.Add(t);
        }
    }
}

Solution

  • Try if this works:

    public static void DrawString(
        Graphics g, string s, Font f, 
        RectangleF r, Color c) 
    {
        StringFormat stringFormat = new StringFormat();
        stringFormat.Alignment = StringAlignment.Far;
        stringFormat.LineAlignment = StringAlignment.Center; // Not necessary here
        g.DrawString(s, f, new SolidBrush(c), r, stringFormat);
    }
    

    using StringFormat example taken from http://msdn.microsoft.com/en-us/library/332kzs7c.aspx