A solid background might get a bit dull, however, so let's create a graphical background by tiling an image across the screen. We'll use a simple cross for our tile so that the end result will look something like a blank graph. Download this image and put it in the directory where you plan to create the next script:
Tiling the above image requires creating a rectangle the size of the image and moving it across the screen, drawing the image at every position:
# Load the background image graphTile = pygame.image.load('graphbackground.bmp').convert()
# Create a rectangle based on the image graphRect = graphTile.get_rect()
# Determine the number of rows and columns of tiles rows = int(256/graphRect.height) + 1 columns = int(256/graphRect.width) + 1
# Loop and draw the background for y in xrange(rows): for x in xrange (columns):
# Start a new row if x == 0 and y > 0: # Move the rectangle graphRect = graphRect.move([-(columns -1 ) * graphRect.width, graphRect.height]) # Continue a row if x > 0: # Move the rectangle graphRect = graphRect.move([graphRect.width, 0])
# Draw the tile screen.blit(graphTile, graphRect)
while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit()
The application starts the same as the previous one, but things change when we get to the background. The first thing we do is load our tile into graphTile. In the process, we call the convert method. This method basically prepares the image to be displayed. We can still draw the tile image without it, but the drawing speed will suffer. Next, we create a rectangle based on the tile image's dimensions. This rectangle will be used to draw the tile on the screen. We then determine the number of rows and columns of tiles there will be, making sure to round up so that we don't end up with less tiles than it takes to fill the screen completely. We loop through so that we can access each row and column, and we use the move method on graphRect, which simply moves the rectangle by the number of pixels specified, to put the rectangle in the appropriate row and column. The tile is drawn (“blitted”) into each position. Finally, we update the screen and wait for the user.
This same method of loading an image and drawing it inside of a rectangle is, of course, not limited to what we use it for here. This principle can be applied anytime you want to load an image. I just think that tiling is a much more productive way to demonstrate images, rather than simply rendering a Python logo in the middle of the screen.