Pygame开发中如何使用blit函数将图片绘制到目标矩形上
实现方法
你只需要提前加载处理好目标图片,替换原有的矩形绘制逻辑即可,具体改动如下:
- 先在初始化部分加载你要贴的图片,将其缩放为和目标矩形一致的50×50尺寸
- 把原代码第50行绘制红色矩形的语句,替换为
blit方法渲染图片
修改后完整代码
import pygame import sys pygame.init() FPS = 60 start_smallfont = pygame.font.SysFont('Corbel', 45) start_text = start_smallfont.render('Start', True, (255, 255, 255)) rect_smallfont = pygame.font.SysFont('Corbel', 33) rect_text = rect_smallfont.render('You', True, (255, 255, 255)) x = 375 y = 335 vel = 0.1 startWIDTH, startHEIGHT = 170, 80 screenWIDTH, screenHEIGHT = 800, 720 WIN = pygame.display.set_mode((screenWIDTH, screenHEIGHT)) pygame.display.set_caption(":D") # 加载并处理玩家图片,请替换为你本地的图片路径 player_image = pygame.image.load("你的图片路径.png").convert_alpha() # 将图片缩放到和原矩形一致的50*50尺寸 player_image = pygame.transform.scale(player_image, (50, 50)) def main(): clock = pygame.time.Clock() run = True while run: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() if event.type == pygame.MOUSEBUTTONDOWN: mouse = pygame.mouse.get_pos() if 800/2-85 <= mouse[0] <= 800/2-85+startWIDTH and 720/2-40 <= mouse[1] <= 720/2-40+startHEIGHT: clock.tick(FPS) run = False while True: global x, y for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() WIN.fill((0, 0, 0)) keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and x > vel: x -= vel if keys[pygame.K_RIGHT] and x < screenWIDTH - 50 - vel: x += vel if keys[pygame.K_UP] and y > vel: y -= vel if keys[pygame.K_DOWN] and y < screenHEIGHT - 50 - vel: y += vel # 替换原来的矩形绘制,渲染图片 WIN.blit(player_image, (x, y)) pygame.display.update() mouse = pygame.mouse.get_pos() if 800/2-85 <= mouse[0] <= 800/2-85+startWIDTH and 720/2-40 <= mouse[1] <= 720/2-40+startHEIGHT: pygame.draw.rect(WIN, (255, 91, 91), (800/2-85, 720/2-40, startWIDTH, startHEIGHT)) else: pygame.draw.rect(WIN, (255, 0, 0), (800/2-85, 720/2-40, startWIDTH, startHEIGHT)) WIN.blit(start_text, (800/2-85+42,720/2-40+20)) pygame.display.update() if __name__ == "__main__": main()
注意事项
- 请把代码里的
"你的图片路径.png"替换为你自己的图片实际存储路径,支持PNG、JPG等常见图片格式 - 如果你的图片本身已经是50×50尺寸,可以删除
pygame.transform.scale那行代码 convert_alpha()方法会保留图片的透明通道,如果是不透明的JPG格式可以换成convert()提升渲染效率
内容的提问来源于stack exchange,提问作者Gratah2
相关产品推荐
相关产品推荐

