title: How do you draw an image to a rotated rectangle in FireMonkey?
body: <p>In FireMonkey, it is simple to draw a bitmap to a source rectangle:</p>
  
  <pre><code>Canvas.DrawBitmap(FBitmap, ImageSrcRect, ImageDstRect, 1);
  </code></pre>
  
  <p>And I'm doing this on a <code>TPaintBox</code>'s canvas. I would instead like to draw the bitmap rotated (and scaled, since the destination size may not be the same as the source size.)</p>
  
  <p>Specifically:</p>
  
  <ul>
  <li>I have two points</li>
  <li>The image should be placed below the centerpoint between these two points</li>
  <li>The image should rotate to follow the angle between the two points</li>
  </ul>
  
  <p>as in this image:</p>
  
  <p><a href="https://i.stack.imgur.com/R6rT5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/R6rT5.png" alt="Desired rotation"></a></p>
  
  <p>One the left is what I can currently do; on the right is what I would like to do.</p>
  
  <p>What's the best way to do it?</p>
  
  <h2>What I've tried</h2>
  
  <p>In order to keep existing code simple (eg, drawing to a destination rectangle, thereby scaling the result) I've been trying to add a rotation matrix to the canvas's matrix before calling the existing DrawBitmap code. For example,</p>
  
  <pre><code>OldMatrix := Canvas.Matrix; // Original, to restore
  
  W := PointB.X - PointA.X;
  H := PointA.Y - PointB.Y;
  RotationMatrix := TMatrix.CreateRotation(-ArcTan2(H, W));
  Canvas.SetMatrix(OldMatrix * RotationMatrix);
  
  Canvas.DrawBitmap(FImage, ImageSrcRect, ImageDstRect, 1);
  
  Canvas.SetMatrix(OldMatrix);
  </code></pre>
  
  <p>and a couple of variations multiplying with the existing matrix, creating an entirely new matrix with both translation and rotation, etc. All these <em>partially</em> work: the rotation angle is correct, but I'm having a lot of trouble getting the position to stay consistent - for example, to rotate around the center point (and this isn't even getting to rotating the top of the bitmap around the point, not rotating around the center.) I've found that the rotated image is offset fine in the bottom right quadrant, but in the other three is offset / translated incorrectly, such as far too far left, or clipped to the leftmost or topmost X or Y position of the two points. I do not know why this is, and it's at this point I'm asking SO for help.</p>
  
  <h2>Details</h2>
  
  <ul>
  <li>Delphi 10 Seattle</li>
  <li>FireMonkey (on Windows)</li>
  <li>Target is the canvas of a <code>TPaintBox</code>, arbitrarily placed. The paint box may itself be on a <code>TScaledLayout</code>.</li>
  <li>The goal is to draw a bitmap to a rotated target rectangle on the paintbox.</li>
  </ul>