Skip to content

Instantly share code, notes, and snippets.

@Zelmoghazy
Last active November 9, 2025 11:22
Show Gist options
  • Select an option

  • Save Zelmoghazy/c5c8dc214cd6c26e14ab84766d726b57 to your computer and use it in GitHub Desktop.

Select an option

Save Zelmoghazy/c5c8dc214cd6c26e14ab84766d726b57 to your computer and use it in GitHub Desktop.
Rounded rectangle drawing algorithm by just drawing arcs and connecting them
void draw_rounded_rectangle_filled_simple(image_view_t *img, i32 x1, i32 y1, i32 x2, i32 y2, i32 radius, color4_t color)
{
if (x1 > x2) { SWAP(x1, x2, i32); }
if (y1 > y2) { SWAP(y1, y2, i32); }
i32 w = x2 - x1 + 1;
i32 h = y2 - y1 + 1;
// Clamp radius to valid range
radius = Clamp(0, radius, MIN(w,h) / 2);
// No rounding draw regular rect
if (radius <= 1) {
draw_rect_solid(img, x1, y1, x2, y2, color);
return;
}
// Test for special cases of straight lines or single point
if (x1 == x2)
{
if (y1 == y2) {
draw_pixel(img, x1, y1, color);
} else {
draw_vline(img, x1, y1, y2, color);
}
return;
}
else
{
if (y1 == y2) {
draw_hline(img, y1, x1, x2, color);
return;
}
}
i32 px = radius;
i32 py = 0;
i32 d = 1 - radius;
while (px >= py)
{
// Top-Left arc
draw_pixel(img, x1 + radius - px, y1 + radius - py, color);
draw_pixel(img, x1 + radius - py, y1 + radius - px, color);
// Top-right arc
draw_pixel(img, x2 - radius + px, y1 + radius - py, color);
draw_pixel(img, x2 - radius + py, y1 + radius - px, color);
// Bottom-left arc
draw_pixel(img, x1 + radius - px, y2 - radius + py, color);
draw_pixel(img, x1 + radius - py, y2 - radius + px, color);
// Bottom-right arc
draw_pixel(img, x2 - radius + px, y2 - radius + py, color);
draw_pixel(img, x2 - radius + py, y2 - radius + px, color);
// Top: connect top-left to top-right
draw_hline(img, y1 + radius - py, x1 + radius - px, x2 - radius + px, color);
draw_hline(img, y1 + radius - px, x1 + radius - py, x2 - radius + py, color);
// Bottom: connect bottom-left to bottom-right
draw_hline(img, y2 - radius + py, x1 + radius - px, x2 - radius + px, color);
draw_hline(img, y2 - radius + px, x1 + radius - py, x2 - radius + py, color);
py++;
if (d < 0) {
d += 2 * py + 1;
} else {
px--;
d += 2 * (py - px) + 1;
}
}
// middle rect
draw_rect_solid_wh(img, x1, y1 + radius, w, h - 2 * radius, color);
}
@Zelmoghazy
Copy link
Author

rounded_rect

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment