Rotating Sprite Image Results in Clipping

I have an action to rotate a sprite by 180, and it works, but it's clipping off a line of pixels from the top of the sprite. I saw some other threads and I was wondering if this is a known bug type issue or if I am approaching this the wrong way.

local function flipCard(index)
    if dealtCards[index] then
        local cardData = dealtCards[index].cardData
        local cardFrontImage = gfx.image.new(cardData.Image)
        dealtCards[index].sprite:setImage(cardFrontImage)
        dealtCards[index].imageName = "CardFront"

        if dealtCards[index].orientation == 'R' then
            dealtCards[index].sprite:setRotation(180)
            local x, y = dealtCards[index].sprite:getPosition()
            dealtCards[index].sprite:moveTo(x + 1, y + 1)
        end

        flipCardIndex = flipCardIndex + 1
    end
end

This is flipping the sprite after it has had it's image changed. Should I instead flip the image and then update the sprite with that flipped image?

Transformations are generally fragile. The size of the image or the sprite, or both, might be causing the recalculated bounding box to be off by just 1 pixel, or the image inside might be out of position by 1 pixel. It's probably a more solid approach to flip the image (kImageFlippedY) rather than rotate the sprite or the image if all you need is a 180° rotation. If you need to see or animate the rotation, you could try expanding the sprite's bounding box by 1 or more pixels in all directions to account for calculations that fall between pixels. I hope this helps!

Here’s an example of expanding the canvas:

-- Create a larger canvas
local largerCanvas = gfx.image.new(cardFrontImage.width + 2, cardFrontImage.height + 2)
gfx.pushContext(largerCanvas)
	gfx.clear(gfx.kColorClear)
	-- Draw the original image centered on the larger canvas
	cardFrontImage:draw(1, 1)
gfx.popContext()

It’s a long-standing bug: image:rotatedImage(90) offsets/crops pixels by (-1,-1)… new in SDK 1.12?

Which is extra fun because iirc there’s some optimizations for rotating images 90°!

3 Likes