📜  如何在 PyGame 中绘制带圆角的矩形?(1)

📅  最后修改于: 2023-12-03 15:08:44.961000             🧑  作者: Mango

如何在 PyGame 中绘制带圆角的矩形?

在 PyGame 中绘制带圆角的矩形可以使用 PyGame 提供的 pygame.draw.rect() 函数和 pygame.draw.circle() 函数结合起来。本文将介绍使用这两个函数的方法。

绘制带圆角的矩形

要绘制带圆角的矩形,我们需要首先绘制一个普通的矩形。然后在矩形的四个角分别绘制圆形,这样就能得到一个带圆角的矩形。

import pygame

pygame.init()

screen = pygame.display.set_mode((400, 400))

rect_width = 200
rect_height = 100
rect_x = (screen.get_width() - rect_width) // 2
rect_y = (screen.get_height() - rect_height) // 2
radius = 30
color = (255, 0, 0)

rect = pygame.Rect(rect_x, rect_y, rect_width, rect_height)

pygame.draw.rect(screen, color, rect)

# 左上角
circle_pos = (rect_x + radius, rect_y + radius)
pygame.draw.circle(screen, color, circle_pos, radius)

# 右上角
circle_pos = (rect_x + rect_width - radius, rect_y + radius)
pygame.draw.circle(screen, color, circle_pos, radius)

# 左下角
circle_pos = (rect_x + radius, rect_y + rect_height - radius)
pygame.draw.circle(screen, color, circle_pos, radius)

# 右下角
circle_pos = (rect_x + rect_width - radius, rect_y + rect_height - radius)
pygame.draw.circle(screen, color, circle_pos, radius)

pygame.display.flip()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

效果如下:

绘制带圆角的矩形

改进

以上代码虽然可行,但是当需要绘制的圆角半径变大时,矩形的边缘会出现锯齿。解决方法是使用 Surface 对象来绘制圆角矩形。

import pygame

pygame.init()

screen = pygame.display.set_mode((400, 400))

rect_width = 200
rect_height = 100
rect_x = (screen.get_width() - rect_width) // 2
rect_y = (screen.get_height() - rect_height) // 2
radius = 30
color = (255, 0, 0)

surf = pygame.Surface((rect_width, rect_height), pygame.SRCALPHA)
pygame.draw.rect(surf, color, pygame.Rect(0, 0, rect_width, rect_height))
pygame.draw.circle(surf, (255, 255, 255, 0), (radius, radius), radius)
pygame.draw.circle(surf, (255, 255, 255, 0), (rect_width - radius, radius), radius)
pygame.draw.circle(surf, (255, 255, 255, 0), (radius, rect_height - radius), radius)
pygame.draw.circle(surf, (255, 255, 255, 0), (rect_width - radius, rect_height - radius), radius)

screen.blit(surf, (rect_x, rect_y))

pygame.display.flip()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

效果如下:

改进后的圆角矩形

总结

使用 PyGame 绘制带圆角的矩形可以使用 pygame.draw.rect() 函数和 pygame.draw.circle() 函数结合起来。如果需要解决锯齿问题,可以使用 Surface 对象来绘制。