Android Code Snippet Draw Bitmap Rotated From Upper-left Corner

I needed to draw a bitmap rotated from the upper-left corner, not the center of the image as the canvas DrawBitmapRotated function does. After looking up the math and coding this again for the I-don't-know-how-many time, I decided to post it here so I could find it quickly in the future, or hopefully save someone else some time.

It should be fairly trivial to change the rotation point to another corner, in my current case I just need it to pivot around the upper-left.
B4X:
'  Rectangle should be the unrotated drawbitmap target rect for the image. Left/top are where to draw it and right/bottom should be the left/top plus the image original width/height.
'  Degrees is the amount to rotate it by.  The returned RECT is where you need to draw using the Canvas.DrawBitmapRotated function.
Private Sub RotateRectUL(Rectangle As Rect, Degrees As Float) As Rect
    Dim pfX As Float
    Dim pfCX As Float
    Dim pfY As Float
    Dim pfCY As Float
    Dim pfTempX As Float
    Dim pfTempY As Float
    Dim pfTheta As Float
    Dim pfRotatedX As Float
    Dim pfRotatedY As Float
    Dim poResult As Rect
    
    pfX = Rectangle.Left
    pfY = Rectangle.Top
    pfCX = pfX + (Rectangle.Width / 2)   ' center of rect is the default rotation point
    pfCY = pfY + (Rectangle.Height / 2)
    ' translate origin point
    pfTempX = pfX - pfCX
    pfTempY = pfY - pfCY
    ' calculate rotation
    pfTheta = (Degrees * cPI / 180)  ' convert to radians
    pfRotatedX = pfTempX * Cos(pfTheta) - pfTempY * Sin(pfTheta)
    pfRotatedY = pfTempX * Sin(pfTheta) + pfTempY * Cos(pfTheta)
    ' translate origin back to upper left
    pfX = pfRotatedX + pfCX - Rectangle.Width + Rectangle.Height
    pfY = pfRotatedY + pfCY - Rectangle.Height
    ' return the new rect
    poResult.Initialize(pfX, pfY, pfX + Rectangle.Width, pfY + Rectangle.Height)
    Return poResult
End Sub
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…