Skip to main content

RotateCenter — wiki

Rotate while keeping an image's center and size. I had to solve this for Trolls Outta Luckland, which needed to rotate an arbitrary image without jittering, resizing, or needing a new hitmask for each rotation. It *only* works with square images.

def rot_center(image, angle):
    """rotate an image while keeping its center and size"""
    orig_rect = image.get_rect()
    rot_image = pygame.transform.rotate(image, angle)
    rot_rect = orig_rect.copy()
    rot_rect.center = rot_image.get_rect().center
    rot_image = rot_image.subsurface(rot_rect).copy()
    return rot_image

This one works with images of any dimension, but does not keep the image's original shape (retaining the original shape could truncate the image).

def rot_center(image, rect, angle):
        """rotate an image while keeping its center"""
        rot_image = pygame.transform.rotate(image, angle)
        rot_rect = rot_image.get_rect(center=rect.center)
        return rot_image,rot_rect