title: WPF: Rotate Rectangle and Place it in Canvas
body: <p>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:</p>
  
  <p><a href="http://www.freeimagehosting.net/uploads/79844652d2.jpg">Rotated Rectangles http://www.freeimagehosting.net/uploads/79844652d2.jpg</a></p>
  
  <p>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.</p>
  
  <p>This is how i tried it so far:</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>I thought the best way to do this is to calculate the x and y offset and position the rectangle by <code>Canvas.SetLeft</code> and <code>Canvas.SetTop</code>. But i have problems figuring out how to do the math. (The y calculation seems to work).</p>
  
  <p>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.)</p>
  
  <p>I hope you understand my problem. It would be nice if you can help me out.</p>