How to draw a rectangle with rounded corner in PyGame?

How to draw a rectangle with rounded corner in PyGame?

In PyGame, drawing a rectangle with rounded corners isn't a built-in function. However, you can achieve this effect by combining regular rectangular drawing with circle drawing for the corners.

Here's a step-by-step guide on how to draw a rectangle with rounded corners in PyGame:

  1. Initialize PyGame and set up a display surface.
  2. Create a function to draw a rectangle with rounded corners.
  3. Call the function.

Here's the code:

import pygame
from pygame.locals import *

pygame.init()

# Colors
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)

# Screen dimensions
SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Rounded Rectangle')


def draw_rounded_rect(surface, color, rect, corner_radius):
    """Draw a rectangle with rounded corners."""
    if corner_radius < 0:
        raise ValueError(f"Radius {corner_radius} must be >= 0")

    if corner_radius == 0:
        pygame.draw.rect(surface, color, rect)
    else:
        # Draw four corners
        pygame.draw.circle(surface, color, (rect.left, rect.top), corner_radius)
        pygame.draw.circle(surface, color, (rect.right, rect.top), corner_radius)
        pygame.draw.circle(surface, color, (rect.left, rect.bottom), corner_radius)
        pygame.draw.circle(surface, color, (rect.right, rect.bottom), corner_radius)
        
        # Draw four sides
        pygame.draw.rect(surface, color, (rect.left, rect.top + corner_radius, rect.width, rect.height - 2*corner_radius))
        pygame.draw.rect(surface, color, (rect.left + corner_radius, rect.top, rect.width - 2*corner_radius, corner_radius))
        pygame.draw.rect(surface, color, (rect.left + corner_radius, rect.bottom, rect.width - 2*corner_radius, -corner_radius))


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

    screen.fill(WHITE)
    draw_rounded_rect(screen, BLUE, Rect(50, 50, 400, 200), 30)
    pygame.display.flip()

pygame.quit()

This code initializes a PyGame window and continuously draws a rectangle with rounded corners until the window is closed. Adjust the Rect and corner_radius values in the draw_rounded_rect function call to change the position, size, and corner roundness of the rectangle.


More Tags

preferences hash jsch powermockito model spread-syntax webkit android-selector flutter-dependencies annotations

More Programming Guides

Other Guides

More Programming Examples