使用pygame描边填充表面

4

期望结果:

  • 在一起的两个工具栏旁边绘制两个相同的工具栏:

    • 颜色=浅灰色
    • 轮廓=黑色

实际结果:

  • 左侧工具栏是:

    • 颜色=浅灰色
    • 轮廓=黑色
  • 右侧工具栏是:

    • 颜色=黑色
    • 轮廓=黑色

问题:如何实现期望的结果?

我的代码:

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
        fill_woutline(self.image, fill_color, outline_color, self.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()

尝试通过在fill_woutline函数中打印outline_colorfill_color的值来调试您的程序。 - Micheal O'Dwyer
@MichealO'Dwyer 我测试了两次,结果都显示正确的数值 (220, 220, 220) (0,0,0)。 - Motonari
我尝试调试程序并发现问题出在使用inflate方法上。至今我还没有找到一个令人满意的方法来绘制你想要的矩形,但希望这能指引你朝着正确的方向前进。 - Micheal O'Dwyer
@MichealO'Dwyer 谢谢,我也是这么想的,但我还没弄清楚为什么... - Motonari
1个回答

2
fill方法的第二个参数指定应该填充的表面区域。如果您在表面上绘制/绘制某些内容,则左上角坐标始终为(0,0),而与表面在屏幕上的位置无关。因此,由于您使用世界坐标传递rect,您永远不会在第二个条形图上绘制任何内容(默认情况下,表面填充为黑色)。
要修复fill_woutline函数,您只需生成一个新的矩形并将其缩小即可。
def fill_woutline(surface, fill_color, outline_color, border=1):
    surface.fill(outline_color)
    surface.fill(fill_color, surface.get_rect().inflate(-border, -border))

1
哦,谢谢,很有道理,这也是为什么第一次运行成功的原因,谢谢。 - Motonari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接