Implementing Blit in PyGame using Python
In this module, we are going to discuss the blit() method that helps us to draw images, text, characters onto the screen of pygame. When we want to perform operations like drawing an image it displays a blank screen if we don’t use blit.
Usage of Blit() in pygame
Generally, blit() refers to portraying contents on to the surface. The general syntax for creating blit() is as follows
pygame.Surface.blit(source,dest)
pygame.Surface is a constructor that helps us to draw images onto the screen.
- source- Represents the image or text name that is to be loaded on to the screen
- dest- Represents the tuple or single value used to position the image or text on the screen.
Example:
Let us take a simple example to demonstrate the functionality of blit().
import pygame import sys pygame.init() sur_obj=pygame.display.set_mode((400,300)) pygame.display.set_caption("Rectangle") sta_img=pygame.image.load("star.png") sur_obj.blit(sta_img,(1,2)) while True: for eve in pygame.event.get(): if eve.type==pygame.QUIT: pygame.quit() sys.exit() pygame.display.update()
If we run the above Pygame code, we will be able to see something like you can see below:
The output will be a blank screen containing the image at pixel coordinates (1,2).
sta_img=pygame.image.load("star.png")
We loaded the image using a PyGame function called pygame.image.load(). This function helps us to load png, jpg files into our code. However, loading doesn’t mean we loaded the image onto a screen. To achieve this we used blit().
sur_obj.blit(sta_img,(1,2))
Here,sur_obj refers to the surface object we have created where we are going to display our image.
Note: The code file and image file must be in the same folder.
The star.png file is given below:
Also, read: Play Video in Python Using Pygame
Leave a Reply