这是我在此处提出的一个问题的后继内容:WinForms: Measure Text With No Padding。问题是,鉴于此代码...
protected override void OnPaint(PaintEventArgs e) {
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
DrawIt(e.Graphics);
}
private void DrawIt(Graphics graphics) {
var text = "123";
var font = new Font("Arial", 72);
// Build a path containing the text in the desired font, and get its bounds.
GraphicsPath path = new GraphicsPath();
path.AddString(text, font.FontFamily, (int)font.Style, font.Size, new Point(0, 0), StringFormat.GenericDefault);
var bounds = path.GetBounds();
// Find center of the form.
var cx = this.ClientRectangle.Left + this.ClientRectangle.Width / 2;
var cy = this.ClientRectangle.Top + this.ClientRectangle.Height / 2;
// Move it where I want it.
var xlate = new Matrix();
xlate.Translate(cx - bounds.Width / 2, cy - bounds.Height / 2);
path.Transform(xlate);
// Draw the path (and a bounding rectangle).
graphics.DrawPath(Pens.Black, path);
bounds = path.GetBounds();
graphics.DrawRectangle(Pens.Blue, bounds.Left, bounds.Top, bounds.Width, bounds.Height);
// This rectangle doesn't use the positioning from Translate but does use the same size.
graphics.DrawRectangle(Pens.Red, cx - bounds.Width / 2, cy - bounds.Height / 2, bounds.Width, bounds.Height);
}
...为什么矩形不重叠?
很显然,当我翻译路径时,我并没有按照后来要绘制的相同单位进行翻译,但是我无所适从。有什么想法吗?
答案 0 :(得分:2)