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

C# WinForms:在正确的位置绘制路径,c#,.net,winforms,graphicspath,C#,.net,Winforms,Graphicspath,这是我在这里提出的一个问题的后续内容:。问题是,考虑到这个代码 protected override void OnPaint(PaintEventArgs e) { e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; DrawIt(e.Graphics); } private void DrawIt(Graphics graphics)

这是我在这里提出的一个问题的后续内容:。问题是,考虑到这个代码

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

看起来很像你想去掉的填充物。雷扎解释了为什么……太好了!谢谢@Reza(和@TaW)。因为我想要的是将文本置于规范位置的中心,所以我只需要更改
xlate.Translate(cx-bounds.Width/2,cy-bounds.Height/2)。。。到
xlate.Translate(cx-bounds.Location.X-bounds.Width/2,cy-bounds.Location.Y-bounds.Height/2)。。。一切都很好。(需要对蓝盒位置进行类似的调整,但它只是为了帮助我调试。)太好了。不客气。事实上,文章试图显示填充,并让您在预期位置绘制红色矩形。你知道你需要的修复方法。