我正在尝试在自定义控件中绘制右对齐文本,但是,由于某种原因,它似乎与我的目标水平位置不对齐,并且字符串之间存在差异。
我可以接受它与我的目标水平位置不完全匹配的事实,但字符串之间的差异在视觉上很糟糕!
任何指针?
隔离代码:
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);
}
}
}