如何使用Pygame绘制图像?我知道如何加载它们。
我已经创建了一个空白窗口。
当我使用
我已经创建了一个空白窗口。
当我使用
screen.blit(blank, (10,10))
时,它不会绘制图像,而是保持屏幕为空白。这是一个典型的布局:
myimage = pygame.image.load("myimage.bmp")
imagerect = myimage.get_rect()
while 1:
your_code_here
screen.fill(black)
screen.blit(myimage, imagerect)
pygame.display.flip()
pygame.image.load
从图像创建一个Surface:my_image_surface = pygame.load.image('my_image.jpg')
convert()
方法,不传入任何参数,以创建一个在屏幕上绘制更快的副本。convert_alpha()
方法,以便图像具有每个像素的透明度。image_surface = pygame.load.image('my_image.jpg').convert()
alpha_image_surface = pygame.load.image('my_icon.png').convert_alpha()
blit
方法在一个Surface上绘制或与另一个Surface混合。blit的第一个参数是要绘制的Surface。第二个参数可以是一个表示左上角的元组(x,y),也可以是一个矩形。对于矩形,只考虑矩形的左上角。值得一提的是,窗口或显示也由一个Surface表示。因此,在窗口中绘制一个Surface与在一个Surface上绘制一个Surface是相同的。window_surface.blit(image_surface, (x, y))
window_surface.blit(image_surface,
image_surface.get_rect(center = window_surface.get_rect().center))
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
pygameSurface = pygame.image.load('apple.png').convert_alpha()
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill((127, 127, 127))
window.blit(pygameSurface, pygameSurface.get_rect(center = window.get_rect().center))
pygame.display.flip()
pygame.quit()
exit()
pygame.image.load
可以加载大多数图像。根据文档,支持以下格式:JPG、PNG、GIF(非动画)、BMP、PCX、TGA(未压缩)、TIF、LBM(和PBM)、PBM(和PGM、PPM)、XPM。
如果您想在Pygame中使用由其他库加载的图像,请参阅:
有关加载可缩放矢量图形(SVG)文件的信息,请参阅:
加载动画GIF文件的方法请参考:
或者查看如何加载NumPy帧:
使用:
import pygame, sys, os
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((100, 100))
player = pygame.image.load(os.path.join("player.png"))
player.convert()
while True:
screen.blit(player, (10, 10))
pygame.display.flip()
pygame.quit()
player.png
。pygame.quit()
will never be executed and true
should be True
- user4734394convert()
返回 新图像;它不会直接更改原始图像。因此,player.convert()
没有任何作用。 - Ted Klein Bergman在使用 blit
或任何其他更新绘图表面的操作之后,你需要调用 pygame.display.flip()
来实际更新显示内容。