Pygame 绘制抗锯齿形状,然后 blitting 到 main window

Pygame drawing antialiased shape and then blitting to main window

我想绘制抗锯齿形状。我知道您可以使用 pygame 的 gfxdraw 模块来完成此操作。但是,它似乎只在直接在主要 window 上绘制时才起作用,这不适合我,因为我打算使用 masks 进行碰撞检查。 因此,需要一个不同的 surface 来创建代表圆圈的遮罩。

如何在 pygame 中做到这一点?

最小工作示例:

import pygame as pg
from pygame import gfxdraw

WIDHT, HEIGHT = 1200, 800
WIN = pg.display.set_mode((WIDHT, HEIGHT))

RADIUS = 80
WHITE = (255, 255, 255)
GREEN = (0, 200, 0)
RED = (200, 0, 0)
TRANS = (1, 1, 1)

class Circle(pg.sprite.Sprite):
    def __init__(self,
                 radius: int,
                 pos: tuple[int, int],
                 color: tuple[int, int, int]):

        super().__init__()
        self.radius = radius
        self.color = color

        self.image = pg.surface.Surface((radius*2, radius*2))
        self.image.fill(TRANS)
        self.image.set_colorkey(TRANS)

        self.rect = self.image.get_rect(center=(pos[0], pos[1]))
        pg.gfxdraw.aacircle(self.image, self.rect.width//2, self.rect.height//2, radius, color)
        pg.gfxdraw.filled_circle(self.image, self.rect.width//2, self.rect.height//2, radius, color)
        self.mask = pg.mask.from_surface(self.image)

    def draw(self):
        WIN.blit(self.image, self.rect)


def main():
    circle_1 = Circle(RADIUS, (500, 500), GREEN)

    running = True
    while running:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running = False

        WIN.fill(WHITE)

        circle_1.draw()
        pg.gfxdraw.filled_circle(WIN, 700, 500, RADIUS, RED)
        pg.gfxdraw.aacircle(WIN, 700, 500, RADIUS, RED)

        pg.display.update()


if __name__ == "__main__":
    main()

您需要使用每像素 alpha 格式创建透明 pygame.Surface。使用 SRCALPHA 标志:

self.image = pg.surface.Surface((radius*2, radius*2))

self.image = pg.surface.Surface((radius*2, radius*2), pg.SRCALPHA)

但是,为了获得最高质量,我建议使用 OpenCV/cv2 (e.g. )