Pygame填充带轮廓表面:双相同工具栏显示异常问题求助
问题分析与解决方案
你的问题出在Bar类中调用fill_woutline函数时传入的rect参数错误。
当你初始化Bar实例时,先获取了self.rect = self.image.get_rect(),然后立刻修改了self.rect.centerx和self.rect.y——这时候self.rect的坐标是相对于游戏窗口(screen)的位置,而非self.image这个Surface自身的坐标系。
但fill_woutline函数是在self.image上绘制内容,这个Surface的坐标系是从自身左上角(0,0)开始的。你传入屏幕坐标的rect,会导致绘制区域完全偏离self.image的可视范围,最终出现右侧工具栏填充错误的问题。
修复步骤
只需要修改Bar类的__init__方法,传给fill_woutline的应该是self.image自身的本地矩形(也就是从(0,0)开始的矩形),而不是已经被设置到屏幕位置的self.rect:
class Bar(pygame.sprite.Sprite): def __init__(self, centerx, y, width, height, fill_color, outline_color, border=1): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((width, height)) # 先创建本地矩形,用于绘制填充和轮廓 local_rect = self.image.get_rect() # 这个rect的坐标是(0,0, width, height),相对于self.image self.rect = self.image.get_rect() self.rect.centerx = centerx self.rect.y = y fill_woutline(self.image, fill_color, outline_color, local_rect, border)
或者更简洁一点,直接传入pygame.Rect(0, 0, width, height)作为绘制用的rect:
fill_woutline(self.image, fill_color, outline_color, pygame.Rect(0, 0, width, height), border)
完整修复后的代码
import pygame import random from os import path WIDTH = 480 HEIGHT = 720 FPS = 30 WHITE = (255, 255, 255) BLACK = (0, 0, 0) LIGHTGREY = (220, 220, 220) pygame.init() pygame.mixer.init() pygame.display.set_caption("tests") screen = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() def fill_woutline(surface, fill_color, outline_color, rect, border=1): surface.fill(outline_color, rect) surface.fill(fill_color, rect.inflate(-border, -border)) class Bar(pygame.sprite.Sprite): def __init__(self, centerx, y, width, height, fill_color, outline_color, border=1): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((width, height)) self.rect = self.image.get_rect() self.rect.centerx = centerx self.rect.y = y # 使用self.image的本地矩形(坐标0,0开始)来绘制 fill_woutline(self.image, fill_color, outline_color, self.image.get_rect(), border) all_bars = pygame.sprite.Group() toolbar = Bar(25, 0, 50, 360, LIGHTGREY, BLACK, 2) toolbar2 = Bar(100, 0, 50, 360, LIGHTGREY, BLACK, 2) all_bars.add(toolbar, toolbar2) while True: clock.tick(FPS) for e in pygame.event.get(): if e.type == pygame.QUIT: pygame.quit() screen.fill(WHITE) all_bars.draw(screen) pygame.display.flip()
这样修改后,两个工具栏都会正确显示为浅灰色填充、黑色轮廓的效果。
内容的提问来源于stack exchange,提问作者Motonari
相关产品推荐
相关产品推荐

