roundrects.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. """
  2. Rounded rectangles in both non-antialiased and antialiased varieties.
  3. """
  4. import pygame as pg
  5. from pygame import gfxdraw
  6. def round_rect(surface, rect, color, rad=20, border=0, inside=(0,0,0,0)):
  7. """
  8. Draw a rect with rounded corners to surface. Argument rad can be specified
  9. to adjust curvature of edges (given in pixels). An optional border
  10. width can also be supplied; if not provided the rect will be filled.
  11. Both the color and optional interior color (the inside argument) support
  12. alpha.
  13. """
  14. rect = pg.Rect(rect)
  15. zeroed_rect = rect.copy()
  16. zeroed_rect.topleft = 0,0
  17. image = pg.Surface(rect.size).convert_alpha()
  18. image.fill((0,0,0,0))
  19. _render_region(image, zeroed_rect, color, rad)
  20. if border:
  21. zeroed_rect.inflate_ip(-2*border, -2*border)
  22. _render_region(image, zeroed_rect, inside, rad)
  23. surface.blit(image, rect)
  24. def _render_region(image, rect, color, rad):
  25. """Helper function for round_rect."""
  26. corners = rect.inflate(-2*rad, -2*rad)
  27. for attribute in ("topleft", "topright", "bottomleft", "bottomright"):
  28. pg.draw.circle(image, color, getattr(corners,attribute), rad)
  29. image.fill(color, rect.inflate(-2*rad,0))
  30. image.fill(color, rect.inflate(0,-2*rad))
  31. def aa_round_rect(surface, rect, color, rad=20, border=0, inside=(0,0,0)):
  32. """
  33. Draw an antialiased rounded rect on the target surface. Alpha is not
  34. supported in this implementation but other than that usage is identical to
  35. round_rect.
  36. """
  37. rect = pg.Rect(rect)
  38. _aa_render_region(surface, rect, color, rad)
  39. if border:
  40. rect.inflate_ip(-2*border, -2*border)
  41. _aa_render_region(surface, rect, inside, rad)
  42. def _aa_render_region(image, rect, color, rad):
  43. """Helper function for aa_round_rect."""
  44. corners = rect.inflate(-2*rad-1, -2*rad-1)
  45. for attribute in ("topleft", "topright", "bottomleft", "bottomright"):
  46. x, y = getattr(corners, attribute)
  47. gfxdraw.aacircle(image, x, y, rad, color)
  48. gfxdraw.filled_circle(image, x, y, rad, color)
  49. image.fill(color, rect.inflate(-2*rad,0))
  50. image.fill(color, rect.inflate(0,-2*rad))