如何缩放列表中的所有Pygame图像?循环缩放无效问题求助
解决Pygame中for循环缩放图像无效果的问题
问题根源
pygame.transform.scale()不会修改传入的原图像对象,而是返回一个新的缩放后的Surface实例。你之前的代码仅调用了缩放方法,但未将返回的新图像替换原列表中的元素,因此原列表里的图像始终保持原始大小,看不到缩放效果。
修复方案
方案1:在循环中更新原列表
修改你的set_colorkey方法,通过索引遍历列表,将缩放后的新图像替换原元素:
def set_colorkey(self): # 使用enumerate同时获取索引和元素,方便更新列表 for idx, pokemon in enumerate(self.pokemon): pokemon.set_colorkey((0, 0, 0)) # 保存缩放后的新图像,并替换原列表对应位置的元素 scaled_img = pygame.transform.scale(pokemon, (120, 120)) self.pokemon[idx] = scaled_img
方案2:加载图像时直接完成缩放(更高效)
将加载、设置透明色、缩放步骤合并,避免后续二次遍历:
self.pokemon = [] # 先整理所有图片路径,让代码更简洁 pokemon_paths = [ '/Users/gersh/PycharmProjects/snakeeo/venv/lib/resources/pokemon/bulbasaur.png', '/Users/gersh/PycharmProjects/snakeeo/venv/lib/resources/pokemon/caterpie.png', '/Users/gersh/PycharmProjects/snakeeo/venv/lib/resources/pokemon/charmander.png', '/Users/gersh/PycharmProjects/snakeeo/venv/lib/resources/pokemon/pidgey.png', '/Users/gersh/PycharmProjects/snakeeo/venv/lib/resources/pokemon/squirtle.png' ] for path in pokemon_paths: img = pygame.image.load(path).convert() img.set_colorkey((0, 0, 0)) # 缩放后直接添加到列表 img = pygame.transform.scale(img, (120, 120)) self.pokemon.append(img)
关键提示
Pygame中所有pygame.transform模块下的方法(如scale、rotate、flip等)都是非破坏性的,它们不会改变传入的原始Surface,只会生成并返回新的Surface对象。如果需要使用处理后的图像,必须将返回值赋值给变量或替换原数据。
内容的提问来源于stack exchange,提问作者user19669080
相关产品推荐
相关产品推荐

