本文介绍了使用矩阵单独旋转的矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一点图纸复杂,你会称它为。我的数学是有点生疏,当涉及到矩阵和形状上绘制旋转。这是一个有点code的:

Having a bit of a drawing complication you would call it. My math is a bit rusty when it comes to Matrices and drawing rotations on shapes. Here is a bit of code:

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旋转。我需要能够为我增加更多的形状单独旋转每个形状。

when I rotate (what I think should be r1) both r1 and r2 rotate. I need to be able to rotate each shape individually as I add more shapes.

推荐答案

我会使用类似这样的功能:

I would use a function similar to this:

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

它使用一个矩阵来在特定点执行的旋转,这应该是每个矩形的中间

It uses a matrix to perform the rotation at a certain point, which should be the middle of each rectangle.

然后在你的paint方法,用它来绘制矩形:

Then in your paint method, use it to draw your rectangles:

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

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

Also, here is the line to connect the two rectangles:

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

下了:

这篇关于使用矩阵单独旋转的矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 03:26