2012-04-18 4 views
6

그리기 복잡함이 조금 있습니다. Mathematics와 모양을 회전 할 때 내 수학은 약간 녹슬니다. 행렬을 사용하여 사각형을 개별적으로 회전하십시오.

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가 모두 회전 : 여기에 코드의 비트입니다. 모양을 추가 할 때 각 도형을 개별적으로 회전 할 수 있어야합니다. 또한 각 직사각형의 중앙되어야하는 특정 지점에서 회전을 수행하는 매트릭스를 사용

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

:

답변

25

는 I이 유사한 기능을 사용할 것이다. 당신의 페인트 방법 다음

, 당신의 사각형 그릴을 사용

:이 설정을 사용

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

: 또한

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

을, 여기에 선이 두 개의 사각형을 연결하는 것입니다

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

결과 :

enter image description here

+1

고맙습니다. 이 예가 실제로 도움이되었습니다. 나는 단지 "g.ResetTransform();이 누락 된 것을 발견했다. 요구. 일단 내가 배치되면 그것은 내 벽을 무너 뜨리고 다시 궤도에 올랐다. 정말 고맙습니다! – Orthmius

관련 문제