WinForms:在正确的位置绘制路径

WinForms: Drawing A Path In The Right Place

这是 follow-on 我在这里问的问题:。问题是,鉴于此代码 ...

    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);
    }

...为什么矩形不重叠?

很明显,当我翻译路径时,我并没有按照我稍后绘制的相同单位进行翻译,但我不知道如何修复它。有什么想法吗?

您对路径的 Bounds 有错误的假设。由于您将字符串添加到路径,从点 (0,0) 开始,您假设路径边界的位置是 (0,0)。那是不正确的。

下图显示了您添加字符串的原点 (0,0) 和路径边界、蓝色矩形之间的关系:

要修复它,在添加字符串并获取其边界后,存储边界的位置:

var p = bounds.Location;

然后在应用变换之后,这样绘制矩形:

graphics.DrawRectangle(Pens.Red, 
     p.X + cx - bounds.Width / 2, p.Y + cy - bounds.Height / 2, 
     bounds.Width, bounds.Height);