Pygame 2D纹理渲染函数高度填充异常该如何解决?
问题根因
问题和texture_count_y变量无关,核心原因是你没有在每一行Y轴循环开始时重置last_texture_x的数值:
第一次遍历完第一行所有X轴纹理块后,last_texture_x已经被递减到小于等于0的数值。进入下一行Y轴的循环时,计算子纹理宽度的逻辑min(last_texture_x,texture.get_width())会返回0或负数,Pygame无法渲染宽高非法的子表面,因此从第二行开始的内容都不会显示,视觉上就只有第一行填充正常。
修复后的代码
def drawTexture(screen,texture,rect): last_texture_y = rect[3] for texture_count_y in range(0, int(rect[3] / texture.get_height()) + 1): # 每行渲染前重置剩余需要填充的宽度 last_texture_x = rect[2] for texture_count_x in range(0, int(rect[2] / texture.get_width()) + 1): blit_w = min(last_texture_x, texture.get_width()) blit_h = min(last_texture_y, texture.get_height()) # 额外加判断避免宽高非法时的无效调用 if blit_w > 0 and blit_h > 0: screen.blit( texture.subsurface(0, 0, blit_w, blit_h), (rect[0] + texture.get_width() * texture_count_x, rect[1] + texture.get_height() * texture_count_y) ) last_texture_x -= texture.get_width() last_texture_y -= texture.get_height()
内容的提问来源于stack exchange,提问作者Arda Yılmaz
相关产品推荐
相关产品推荐

