在pygame中用轮廓填充曲面

时间:2018-01-06 11:59:17

标签: python pygame

期望的结果:

  • 彼此相邻绘制两个相同的工具栏:

    • Color = lightgrey
    • Outline = black

实际结果:

  • 左手工具栏是:

    • Color = lightgrey
    • Outline = black
  • 右手工具栏是:

    • 颜色=黑色
    • Outline = black

问题:我如何达到预期的效果?

我的代码:

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()

1 个答案:

答案 0 :(得分:0)

fill方法的第二个参数指定应填充的曲面区域。如果您在表面上进行blit / draw事件,那么topleft coords将始终(0,0)独立于屏幕上的表面位置。所以,因为你传递rect s与世界坐标,你永远不会在第二个条上绘制任何东西(表面默认为黑色)。

要修复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))