-
- if the image has no transparent pixels:
.convert()
- if the image has no transparent pixels:
-
- if the image has transparent pixels:
.convert_alpha()
, this will make your game run much faster.
- if the image has transparent pixels:
🟠 When importing images into Pygame, converting them to a suitable format can significantly enhance performance. Here's how to handle different types of images:
🔸 For images without transparency:
-
- Use the
.convert()
method.
- Use the
-
-
- This will optimize the image's color format for faster rendering, as it ✋ simplifies the image data without the need for transparency support.
-
a simple background image
or a sprite
with a solid color background.
- Use the
.convert()
method to optimize these images. This converts the image to a format that Pygame can quickly render because it doesn’t need to manage transparency.
background = pygame.image.load('background.png').convert()
- check the video by 🌟 Code with Russ
🔸 For images with transparency:
-
- Use the
.convert_alpha()
method.
- Use the
-
-
- This method preserves the transparency information and converts the image into a format that maintains the
alpha channel
, ✋ ensuring both quality and performance.
- This method preserves the transparency information and converts the image into a format that maintains the
-
-
a character
sprite with atransparent background
or a UI icon with see-through areas. -
- Use the
.convert_alpha()
method for these images.
- Use the
-
-
- This method preserves the transparency of the image, ensuring that the alpha channel (which controls transparency) is maintained for accurate rendering.
-
character = pygame.image.load('character.png').convert_alpha()
🧶 Properly converting your images ensures smoother gameplay and better performance by aligning image formats with Pygame's rendering capabilities.
# 18 - convert
player_surf = pygame.image.load(image_path).convert()
-
- As you can see, the image has a black background, indicating that it contains alpha values.
simplescreenrecorder-2024-08-17_23.30.51.mp4
player_surf = pygame.image.load(image_path).convert_alpha()
import pygame
# from os.path import join / path for img (important!!)
import os
pygame.init()
# path for img (important!!)
script_dir = os.path.dirname(__file__)
# --- window
WINDOW_WIDTH, WINDOW_HEIGHT = 1280, 720
#3
display_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# --- window
pygame.display.set_caption("Space shooter")
running = True
surf = pygame.Surface((100,200))
surf.fill('orange')
x = 100
image_path = os.path.join(script_dir, '..', 'images', 'player.png')
# ✋
player_surf = pygame.image.load(image_path).convert_alpha()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
display_surface.fill("lavenderblush2")
x += 0.1
display_surface.blit(player_surf, (x,150))
pygame.display.update()
pygame.quit()