1. *** New version of B4J is available ***
    B4J v7.8
    Dismiss Notice

Android Code Snippet Draw Bitmap Rotated From Upper-left Corner

Discussion in 'Code Snippets' started by Jeffrey Cameron, Apr 11, 2019.

  1. Jeffrey Cameron

    Jeffrey Cameron Active Member Licensed User

    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.
    '  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
    GMan likes this.
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice