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

时间:2018-06-24 01:46:26

标签: c# .net winforms graphicspath

这是我在此处提出的一个问题的后继内容: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);
    }

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

enter image description here

很显然,当我翻译路径时,我并没有按照后来要绘制的相同单位进行翻译,但是我无所适从。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

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

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

enter image description here

要解决此问题,请在添加字符串并获得边界后,存储边界的位置:

var p = bounds.Location;

然后应用转换后,以这种方式绘制矩形:

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