7

有一点绘图的复杂性,你会称之为。当涉及到矩阵和在形状上绘制旋转时,我的数学有点生疏。这是一段代码:

private void Form1_Paint(object sender, PaintEventArgs e)
    {
        g = e.Graphics;
        g.SmoothingMode = SmoothingMode.HighQuality;
        DoRotation(e);
        g.DrawRectangle(new Pen(Color.Black), r1);
        g.DrawRectangle(new Pen(Color.Black), r2);

        // draw a line (PEN, CenterOfObject(X, Y), endpoint(X,Y) )
        g.DrawLine(new Pen(Color.Black), new Point((r1.X + 50), (r1.Y + 75)), new Point((/*r1.X + */50), (/*r1.Y - */25)));

        this.lblPoint.Text = "X-pos: " + r1.X + " Y-pos: " + r1.Y;

        //this.Invalidate();
    }
    public void DoRotation(PaintEventArgs e)
    {
        // move the rotation point to the center of object
        e.Graphics.TranslateTransform((r1.X + 50), (r1.Y + 75));
        //rotate
        e.Graphics.RotateTransform((float)rotAngle);
        //move back to the top left corner of the object
        e.Graphics.TranslateTransform(-(r1.X + 50), -(r1.Y + 75));
    }
    public void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        case Keys.T:
                rotAngle += 1.0f;
    }

当我旋转(我认为应该是 r1)时,r1 和 r2 都会旋转。当我添加更多形状时,我需要能够单独旋转每个形状。

4

1 回答 1

27

我会使用与此类似的功能:

public void RotateRectangle(Graphics g, Rectangle r, float angle) {
  using (Matrix m = new Matrix()) {
    m.RotateAt(angle, new PointF(r.Left + (r.Width / 2),
                              r.Top + (r.Height / 2)));
    g.Transform = m;
    g.DrawRectangle(Pens.Black, r);
    g.ResetTransform();
  }
}

它使用矩阵在某个点执行旋转,该点应该是每个矩形的中间。

然后在您的绘画方法中,使用它来绘制您的矩形:

g.SmoothingMode = SmoothingMode.HighQuality;
//g.DrawRectangle(new Pen(Color.Black), r1);
//DoRotation(e);
//g.DrawRectangle(new Pen(Color.Black), r2);

RotateRectangle(g, r1, 45);
RotateRectangle(g, r2, 65);

此外,这是连接两个矩形的线:

g.DrawLine(Pens.Black, new Point(r1.Left + r1.Width / 2, r1.Top + r1.Height / 2),
                       new Point(r2.Left + r2.Width / 2, r2.Top + r2.Height / 2));

使用这些设置:

private Rectangle r1 = new Rectangle(100, 60, 32, 32);
private Rectangle r2 = new Rectangle(160, 100, 32, 32);

导致:

在此处输入图像描述

于 2012-04-18T13:40:36.810 回答