2013-03-14 120 views
0

我想要的是移動物體並沿其中心點旋轉。我使用Matrix類進行轉換:如何在這種情況下指定圖像位置?

private void pictureBox1_Paint(object sender, PaintEventArgs e) 
    { 
     e.Graphics.ResetTransform(); 
     Matrix transformationMatrix = new Matrix(); 
     transformationMatrix.RotateAt(rot, new PointF(img.Size.Width/2, img.Size.Height/2)); 
     e.Graphics.Transform = transformationMatrix; 
     e.Graphics.DrawImage(img, 0, 0, img.Size.Width, img.Size.Height); 
    } 

上面的代碼將沿着圖像的中心旋轉圖像。

但是,如果我嘗試將其移動(我把圖像在圖片框的中心),圖像不再旋轉沿着它的中心點。

e.Graphics.DrawImage(img, (pictureBox1.Width - img.Size.Width)/2, (pictureBox1.Height - img.Size.Height)/2, img.Size.Width, img.Size.Height); 

現在我想我必須使用Translate功能來指定位置,但我不知道該怎麼做。翻譯採取相對的立場。我想用中心點指定圖像位置,並能夠沿着它的中心旋轉它。

更新2:

修改後的代碼看起來像這樣

origin.X = 50; 
origin.Y = 50; 

    private void pictureBox1_Paint(object sender, PaintEventArgs e) 
    { 
     e.Graphics.TranslateTransform(origin.X, origin.Y); 
     e.Graphics.RotateTransform(rot); 
     e.Graphics.DrawImage(img, -img.Size.Width, -img.Size.Height/2, img.Size.Width, img.Size.Height); 
    } 

所以我定義的起源點到我的指定圖像的位置。但它仍然不會沿着它的中心旋轉。

enter image description here

+0

這是WPF/Silverlight,不是嗎? – 2013-03-14 19:53:02

+0

不,Windows窗體。 – Pablo 2013-03-14 19:53:25

+0

也許這篇文章會很有用:http://stackoverflow.com/questions/636081/how-to-rotate-scale-and-translate-a-matrix-all-at-once-in-c?rq=1 – Lainezor 2013-03-14 20:03:42

回答

1

是的,你要使用的翻譯功能。下面是我寫了另外一個問題,說明如何平移和旋轉和形象的例子:

https://stackoverflow.com/a/10956388/351385

更新

你想要做的是設置轉換點在點什麼窗口中你的對象的中心。這會導致顯示屏的[0, 0]點成爲該點,所以任何旋轉都會在其周圍發生。然後,當您繪製圖像時,使用圖像[image width/2, image height/2]的中點作爲DrawImage方法的座標。

再次更新

對不起,傳遞給的DrawImage的座標在圖像[0 - width/2, 0 - height/2]的否定中點。

+0

謝謝,我更新了我的帖子。 – Pablo 2013-03-14 21:00:33

+0

@Pablo我已經更新了我的答案。 – Tergiver 2013-03-14 21:15:03

+0

請參閱更新2.它看起來像在我的情況下更難以實現。基本上圖像是垂直放置在方形框架中的線,水平居中(如果描述不清晰,可以將其張貼)。紅圈是320x320平方的中點。 – Pablo 2013-03-14 21:51:48