How to draw a rectangle with rounded corner in PyGame? (original) (raw)

Last Updated : 16 Mar, 2022

Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language. In this article, we will see how can we draw a rectangle with rounded corners in Pygame.

Functions Used:

Syntax:

rect(surface, color, rect, width=0, border_radius=0, border_top_left_radius=-1, border_top_right_radius=-1, border_bottom_left_radius=-1, border_bottom_right_radius=-1)

The border_radius parameters were only added to PyGame version 2.0.0.dev8.

Approach

Example 1: This example draws a rectangle with all corner rounded

Python3 `

Importing the library

import pygame

Initializing Pygame

pygame.init()

Initializing surface

surface = pygame.display.set_mode((400, 300))

Initializing Color

color = (48, 141, 70)

Drawing Rectangle

pygame.draw.rect(surface, color, pygame.Rect(30, 30, 60, 60), 2, 3) pygame.display.flip()

`

Output:

Not just this, Pygame can be used to round even only one corner as per requirement. Given below is the implementation using the above approach.

Example 2: This example draws a rectangle with only the top right corner rounded.

Python3 `

Importing the library

import pygame

Initializing Pygame

pygame.init()

Initializing surface

surface = pygame.display.set_mode((400, 300))

Initializing Color

color = (48, 141, 70)

Drawing Rectangle

pygame.draw.rect(surface, color, pygame.Rect(30, 30, 60, 60), 2, 0, 0, 3)

Displaying Object

pygame.display.flip()

`

Output:

Example 3: This example uses keyword arguments to draw a rectangle with the bottom right corner rounded.

Python3 `

Importing the library

import pygame

Initializing Pygame

pygame.init()

Initializing surface

surface = pygame.display.set_mode((400, 300))

Initializing Color

color = (48, 141, 70)

Drawing Rectangle

pygame.draw.rect(surface, color, pygame.Rect( 30, 30, 60, 60), 2, border_bottom_right_radius=5)

Displaying Object

pygame.display.flip()

`

Output: