WPF: Rotate Rectangle and Place it in Canvas
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 cl开发者_开发技巧ipped 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.
The solution is actually a lot simpler than you may have guessed. Instead of using RenderTransform
, use LayoutTransform
instead. It takes the same kinds of transformations but instead of applying them to the rendered output of the element during the rendering pass, it alters the layout space of the element during the layout pass. So the following XAML produces the result you showed in the second example in your screen shot.
<Canvas Width="640" Height="480">
<Rectangle Fill="Blue" Width="200" Height="80">
<Rectangle.LayoutTransform>
<RotateTransform Angle="-45"/>
</Rectangle.LayoutTransform>
</Rectangle>
</Canvas>
Note that this does not work in Silverlight because Silverlight doesn't support LayoutTransform.
精彩评论