问题
I am a beginner in Python and I am not clear about the function surface.blit()
. What does it do? How does it works?
I have come across the following points as to how to create it.
- Create a canvas of desired size
- Create a surface of smaller size containing the object to be displayed.
- Define the Rect value of the surface.
- Blit (overlap) the surface on the canvas at the rect position
Syntax: canvas.blit(surface, surfacerect)
Why is only rect used? Can it be any other shape?
回答1:
Putting this in real terms may help, although as simply put as possible -> blitting is drawing
Going through each of the steps you have mentioned:
- Create a canvas of a desired size
This is our window, created by screen = pygame.display.set_mode((width,height))
. Where screen
is the canvas name. Eventually everything will need to be drawn onto this canvas so that we can see it.
- Create a surface of smaller size containing the object to be displayed
This is a surface that we will populate with objects such as images. It does not need to be smaller than the window size and it can be moved around freely.
- Define a Rect value of the surface
When you create a surface using something like background = pygame.Surface((width,height))
you specify it's size. The images or drawn items on the surface can be any shape or size but they must all be contained within the bounds set by this width and height.
- Blit (overlap) the surface on the canvas at the rect position
Now the all important bit. We need to get this surface (background) and draw it onto the window. To do this we will call screen.blit(background,(x,y))
where (x,y) is the position inside the window where we want the top left of the surface to be. This function says take the background surface and draw it onto the screen and position it at (x,y).
A simple example:
import pygame
pygame.init()
#### Create a canvas on which to display everything ####
window = (400,400)
screen = pygame.display.set_mode(window)
#### Create a canvas on which to display everything ####
#### Create a surface with the same size as the window ####
background = pygame.Surface(window)
#### Create a surface with the same size as the window ####
#### Populate the surface with objects to be displayed ####
pygame.draw.rect(background,(0,255,255),(20,20,40,40))
pygame.draw.rect(background,(255,0,255),(120,120,50,50))
#### Populate the surface with objects to be displayed ####
#### Blit the surface onto the canvas ####
screen.blit(background,(0,0))
#### Blit the surface onto the canvas ####
#### Update the the display and wait ####
pygame.display.flip()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
#### Update the the display and wait ####
pygame.quit()
来源:https://stackoverflow.com/questions/37800894/what-is-the-surface-blit-function-in-pygame-what-does-it-do-how-does-it-work