Info_edupage/UI/rounded_rect.py

52 lines
2.3 KiB
Python
Raw Normal View History

2021-08-31 22:22:56 +02:00
import pygame.gfxdraw
def draw_rounded_rect(surface, rect, color, corner_radius):
if rect.width < 2 * corner_radius or rect.height < 2 * corner_radius:
raise ValueError(f"Both height (rect.height) and width (rect.width) must be > 2 * corner radius ({corner_radius})")
# need to use anti aliasing circle drawing routines to smooth the corners
pygame.gfxdraw.aacircle(surface, rect.left+corner_radius, rect.top+corner_radius, corner_radius, color)
pygame.gfxdraw.aacircle(surface, rect.right-corner_radius-1, rect.top+corner_radius, corner_radius, color)
pygame.gfxdraw.aacircle(surface, rect.left+corner_radius, rect.bottom-corner_radius-1, corner_radius, color)
pygame.gfxdraw.aacircle(surface, rect.right-corner_radius-1, rect.bottom-corner_radius-1, corner_radius, color)
pygame.gfxdraw.filled_circle(surface, rect.left+corner_radius, rect.top+corner_radius, corner_radius, color)
pygame.gfxdraw.filled_circle(surface, rect.right-corner_radius-1, rect.top+corner_radius, corner_radius, color)
pygame.gfxdraw.filled_circle(surface, rect.left+corner_radius, rect.bottom-corner_radius-1, corner_radius, color)
pygame.gfxdraw.filled_circle(surface, rect.right-corner_radius-1, rect.bottom-corner_radius-1, corner_radius, color)
rect_tmp = pygame.Rect(rect)
rect_tmp.width -= 2 * corner_radius
rect_tmp.center = rect.center
pygame.draw.rect(surface, color, rect_tmp)
rect_tmp.width = rect.width
rect_tmp.height -= 2 * corner_radius
rect_tmp.center = rect.center
pygame.draw.rect(surface, color, rect_tmp)
def draw_bordered_rounded_rect(surface, rect, color, border_color, corner_radius, border_thickness):
if corner_radius < 0:
raise ValueError(f"border radius ({corner_radius}) must be >= 0")
rect_tmp = pygame.Rect(rect)
center = rect_tmp.center
if border_thickness:
if corner_radius <= 0:
pygame.draw.rect(surface, border_color, rect_tmp)
else:
draw_rounded_rect(surface, rect_tmp, border_color, corner_radius)
rect_tmp.inflate_ip(-2*border_thickness, -2*border_thickness)
inner_radius = corner_radius - border_thickness + 1
else:
inner_radius = corner_radius
if inner_radius <= 0:
pygame.draw.rect(surface, color, rect_tmp)
else:
draw_rounded_rect(surface, rect_tmp, color, inner_radius)