Drawing an image
Drawing an image file (jpeg or png) is really easy! Only two lines of code needed. The following assumes your image files are located in your PyCharms project folder.
- Load the image to a variable. Do this only once, typically where you declare your colours, fonts etc. It really is important that your pygame.image.load is not in your game loop. Every time you run it you are reloading the file into memory, slowing your system down!
IMAGE = pygame.image.load("image.jpg").convert_alpha()
- Draw the full image onto the screen.
(x,y)is the coordinates to place the top-left corner of the image on your screen. Do this where you would have used
window.blit(IMAGE, (x, y))
Other useful image functionality
To only render part of an image onto the screen, you can supply the coordinates of the rectangle within the image you want to use.
window.blit(IMAGE, (window-x, window-y), (image-x, image-y, image-width, image-height))
To resize an image before drawing it onto the screen.
picture = pygame.image.load(filename) picture = pygame.transform.scale(picture, (newWidth, newHeight))
To rotate an image
- Will rotate counter-clockwise. Use a negative number to rotate clockwise.
- Unless rotating by 90 degree increments, the image will be padded larger to hold the new size. If the image has pixel alphas, the padded area will be transparent. Otherwise pygame will pick a color that matches the Surface colorkey or the topleft pixel value.
originalPicture = pygame.image.load(filename) rotatedPicture = pygame.transform.scale(originalPicture, 90)
To get a colour at a given pixel
pixel_colour = window.get_at(( x , y ))