Menu
CoddyTech

Scale an Image

Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 8 of 36.

The boss of a level should look big, and a lives counter needs small ships. The same files can do both: scaling makes a resized copy.

boss = pygame.transform.scale_by(boss, 2)
icon = pygame.transform.scale(ship, (32, 32))

scale_by(image, 2) multiplies both sides by 2: the 64 by 64 boss becomes 128 by 128. scale(image, (w, h)) makes it exactly w by h pixels, even if that stretches it.

Scaling is slow next to a blit, and each new copy blurs or blocks the pixels a little more. Scale once, before the loop, from the original file, and draw the scaled copy every frame.

Make the Rect after scaling. A Rect made from the 64 by 64 picture would be the old size, and center=(320, 150) would put the big boss off centre.

challenge icon

Challenge

Easy
  1. Scale the boss by 2 before the loop, then make boss_rect from the scaled image, centred at (320, 150).
  2. Make icon: the ship scaled to (32, 32).
  3. Draw icon three times, with its top left at (10, 10), (50, 10) and (90, 10).

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Boss Fight")
clock = pygame.time.Clock()

boss = pygame.image.load("assets/images/boss.png").convert_alpha()
boss_rect = boss.get_rect(center=(320, 150))
ship = pygame.image.load("assets/images/ship.png").convert_alpha()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((20, 22, 40))
    screen.blit(boss, boss_rect)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Sprites and Images

Practice on your own: Pygame playground