首页 > 解决方案 > WinForms:在正确的位置绘制路径

问题描述

这是我在这里提出的一个问题的后续: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);
    }

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

在此处输入图像描述

显然,当我翻译路径时,我并没有使用稍后绘制它们的相同单位进行翻译,但我不知道如何修复它。有任何想法吗?

标签: c#.netwinformsgraphicspath

解决方案


Bounds您对路径有错误的假设。由于您将字符串添加到路径,从 point 开始(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);

推荐阅读