将 pygame 表面设置为圆角

Setting a pygame surface to have rounded corners

Rectangle class 从 pygame.sprite 延伸而来。我想使用 set_rounded 来修改矩形角的圆度。例如https://imgur.com/2N5NHlg

class Rectangle(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.original_image = pg.Surface((10, 10))
        self.image = self.original_image
        self.rect = self.image.get_rect()


    def set_rounded(self, roundness):
        pass

roundness 参数将确定圆角矩形的半径。

你可以通过设置函数pygame.draw.rect的关键字参数border_radius来实现你想要的。

创建一个与图像大小和每个像素 alpha 相同的矩形 (SRCALPHA),然后绘制一个完全白色、不透明的圆角图像:

size = self.original_image.get_size()
self.rect_image = pg.Surface(size, pg.SRCALPHA)
pg.draw.rect(self.rect_image, (255, 255, 255), (0, 0, *size), border_radius=roundness)

复制原始图像并使用BLEND_RGBA_MIN混合模式将矩形与图像混合(参见pygame.Surface.blit):

self.image = self.original_image.copy().convert_alpha()
self.image.blit(self.rect_image, (0, 0), None, pg.BLEND_RGBA_MIN) 

请注意,关键字属性 border_radius 是一项新功能。您必须使用最新的 pygame 版本 (2.0.0.dev10)。

如果不能使用2.0.0.dev10版本,就需要自己把圆角矩形贴在一起了:

class Rectangle(pg.sprite.Sprite):
    # [...]

    def set_rounded(self, roundness):
        size = self.original_image.get_size()
        self.rect_image = pg.Surface(size, pg.SRCALPHA)
        
        #pg.draw.rect(self.rect_image, (255, 255, 255), (0, 0, *size), border_radius=roundness)

        r, c = roundness, (255, 255, 255)
        pg.draw.rect(self.rect_image, c, (r, 0, size[0]-2*r, size[1]))
        pg.draw.rect(self.rect_image, c, (0, r, size[0], size[1]-2*r))
        for cpt in [(r, r), (size[0]-r, r), (r, size[1]-r), (size[0]-r, size[1]-r)]:  
            pg.draw.circle(self.rect_image, c, cpt, r)

        self.image = self.original_image.copy().convert_alpha()
        self.image.blit(self.rect_image, (0, 0), None, pg.BLEND_RGBA_MIN) 

看例子:

import pygame as pg

class Rectangle(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.original_image = pg.Surface((100, 100))
        self.original_image.fill((255, 0, 0))
        self.image = self.original_image
        self.rect = self.image.get_rect()

    def set_rounded(self, roundness):
        size = self.original_image.get_size()
        self.rect_image = pg.Surface(size, pg.SRCALPHA)
        pg.draw.rect(self.rect_image, (255, 255, 255), (0, 0, *size), border_radius=roundness)

        self.image = self.original_image.copy().convert_alpha()
        self.image.blit(self.rect_image, (0, 0), None, pg.BLEND_RGBA_MIN) 

pg.init()
window = pg.display.set_mode((200, 200))

rect_object = Rectangle()
rect_object.set_rounded(30)
rect_object.rect.center = window.get_rect().center
group = pg.sprite.Group(rect_object)

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

    window.fill((128, 128, 128))
    group.draw(window)
    pg.display.flip()