2016-04-11 72 views
0

我有UserControl的大小300 * 200。 和尺寸爲300 * 200的矩形。根據用戶控件旋轉和縮放矩形

graphics.DrawRectangle(Pens.Black, 0, 0, 300, 200); 

當我在userControl中旋轉矩形30度,我得到旋轉矩形,但它是超大。

PointF center = new PointF(150,100); 
graphics.FillRectangle(Brushes.Black, center.X, center.Y, 2, 2); // draw center point. 

using (Matrix matrix = new Matrix()) 
{ 
     matrix.RotateAt(30, center); 
     graphics.Transform = matrix; 
     graphics.DrawRectangle(Pens.Black, 0, 0, 300, 200); 
     graphics.ResetTransform(); 
} 

我想合適的矩形像實際結果。 Check Image here

任何人都可以解決這個問題。

感謝。

+0

它做的正是你要求它什麼。它旋轉。如果你用一張紙做,你會發現它是一樣的。你想要的是旋轉和規模我假設。 – Noctis

+0

@Noctis - 你有任何解決方案嗎? –

+0

如果你使用的是WPF,你也可以簡單地使用'LayoutTransform'而不是'RenderTransform',並且達到相同的結果,減去數學... – Noctis

回答

1

這是一個數學問題而不是編程問題。

計算以弧度旋轉任意角度的任何矩形的博寧盒。

var newWidth= Math.Abs(height*Math.Sin(angle)) + Math.Abs(width*Math.Cos(angle)) 
var newHeight= Math.Abs(width*Math.Sin(angle)) + Math.Abs(height*Math.Cos(angle)) 

x和y的計算規模:

scaleX = width/newWidth; 
scaleY = height/newHeight; 

它應用到您的矩形。

編輯: 適用於你的例子:

PointF center = new PointF(150, 100); 
    graphics.FillRectangle(Brushes.Black, center.X, center.Y, 2, 2); // draw center point. 
    var height = 200; 
    var width = 300; 
    var angle = 30; 
    var radians = angle * Math.PI/180; 
    var boundingWidth = Math.Abs(height * Math.Sin(radians)) + Math.Abs(width * Math.Cos(radians)); 
    var boundingHeight = Math.Abs(width * Math.Sin(radians)) + Math.Abs(height * Math.Cos(radians)); 
    var scaleX = (float)(width/boundingWidth); 
    var scaleY = (float)(height/boundingHeight); 
    using (Matrix matrix = new Matrix()) 
    { 
     matrix.Scale(scaleX, scaleY, MatrixOrder.Append); 
     matrix.Translate(((float)boundingWidth - width)/2, ((float)boundingHeight - height)/2); 
     matrix.RotateAt(angle, center); 
     graphics.Transform = matrix; 
     graphics.DrawRectangle(Pens.Black, 0, 0, width, height); 
     graphics.ResetTransform(); 
    } 
+0

感謝您的建議。但是如果矩形的大小改變意味着它是300 * 200。 –

+1

@SagarKhade然後你需要再次計算它。據我所知,'a^2 + b^2 = c^2'仍然是真的:) – Noctis

+0

但我的意思是說,如果usercontrol的大小是300 * 200固定。矩形也是300 * 200,角度變爲30.那麼? –