i have a problem with rotating a rectangle and place it on a canvas in a certain way. Here is what i try to achieve:
Rotated Rectangles http://www.freeimagehosting.net/uploads/79844652d2.jpg
The big rectangle in the picture is my canvas. The smaller rectangle is my rectangle i want to rotate. When i rotate the rectangle (dotted rectangle), it gets clipped of course. To avoid this, i want to reposition the rectangle like in the picture on the right side.
This is how i tried it so far:
Rectangle rect = new Rectangle();
rect.Width = 100;
rect.Height = 50;
int angle = 30;
rect.RenderTransform = new RotateTransform(angle, rect.Width/2, rect.Height/2);
canvas.Children.Add(rect);
double x = Math.Cos(30) * (rect.Width / 2) + Math.Sin(30) * (rect.Height / 2) - rect.Width / 2;
double y = Math.Sin(30) * (-rect.Width / 2) + Math.Cos(30) * (rect.Height / 2) - rect.Height / 2;
Canvas.SetLeft(rect, x);
Canvas.SetTop(rect, y);
I thought the best way to do this is to calculate the x and y offset and position the rectangle by Canvas.SetLeft
and Canvas.SetTop
. But i have problems figuring out how to do the math. (The y calculation seems to work).
Actually i want to place several rectangles on the canvas at random positions. The rotation angle can be a value between -45 and 45 degree and the rectangle sizes can be random values, too. But the rectangles should always be fully visible in the canvas so i need to know the offsets for the bounds of the position coordinates. (The rectangles could overlap themselves.)
I hope you understand my problem. It would be nice if you can help me out.