Using a matrix to rotate rectangles individually

后端 未结 1 859
盖世英雄少女心
盖世英雄少女心 2020-11-29 04:52

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:

         


        
相关标签:
1条回答
  • 2020-11-29 05:24

    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.

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

    Using these settings:

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

    resulted in:

    enter image description here

    0 讨论(0)
提交回复
热议问题