Rotating images off-center without sprites

Hi, I would like to ask how you solve rotations for images without using sprites. Specifically, I am referring to rotating an image off-center. The documentation for image:drawRotated(x, y, angle, [scale, [yscale]]) describes that the image is drawn centered on the x, y point. Is there any way to make it possible to rotate the image from a point other than the center point without having to maintain x and y manually?

Thanks for the answers

How about using :rotatedImage and a bit of trig? It won't be terribly performant, but if you're okay with using drawRotated I guess that's not a problem.

offsetX and offsetY are proportional (0 to 1).

function drawOffsetRotated(image, x, y, offsetX, offsetY, angle)
    -- convert proportional offset to pixel offset
    local w, h = image:getSize()
    local offsetX_pixels = (0.5 - offsetX) * w
    local offsetY_pixels = (0.5 - offsetY) * h
    
    -- calculate the new center for drawing the rotated image
    local cosAngle = math.cos(math.rad(angle))
    local sinAngle = math.sin(math.rad(angle))
    local centerX = x + offsetX_pixels * cosAngle - offsetY_pixels * sinAngle
    local centerY = y + offsetX_pixels * sinAngle + offsetY_pixels * cosAngle
    
    -- create then draw a rotated version of the image
    local rotatedImage = image:rotatedImage(angle)
    rotatedImage:drawCentered(centerX, centerY)
end
2 Likes

Oh thank, it works. i've been able to improve my rendering pipeline thanks to your snippet. But is there a reason why I shouldn't be okay with using drawRotated (i'm just getting familiar with the SDK so please bear with me)? I know the documentation states that transform functions can be slow, is that the reason? Thanks

EDIT: I'm caching the result of image:rotatedImage and only invoking it again when the angle or scale changes

1 Like

Iā€™m glad it worked! :sweat_smile:

Rotating images each update can be slow, but pre-caching the rotations is fine.

1 Like