Reputation:
Is there a way to draw a semicircle in Pygame? Something like this:
pygame.surface.set_clip()
will not work for this - I need circles that look like pie slices as well, like this one:
Upvotes: 3
Views: 8132
Reputation: 31
import pygame
from math import sin,cos,radians
#function to draw pie using parametric coordinates of circle
def pie(scr,color,center,radius,start_angle,stop_angle):
theta=start_angle
while theta <= stop_angle:
pygame.draw.line(scr,color,center,
(center[0]+radius*cos(radians(theta)),center[1]+radius*sin(radians(theta))),2)
theta+=0.01
#for example:-
if __name__=="__main__":
winWidth,winHeight=500,500
scr=pygame.display.set_mode((winWidth,winHeight))
pie(scr,(255,0,0),(winWidth//2,winHeight//2),250,0,60)
pygame.display.update()
this is result of this example
The way this code solves the issue is by rotating a line of width 2 around a circle so that the overlap between any two lines doesn't leave a gap
The real life analogy would be to think about a thick clock hand moving around a clock and taking pictures of it so that when you overlay the images you get a filled in sector of a circle.
Upvotes: 3
Reputation: 143207
PyGame
has no function to create filled arc/pie
but you can use PIL/pillow
to generate bitmap with pieslice
and convert to PyGame
image to display it.
import pygame
#import pygame.gfxdraw
from PIL import Image, ImageDraw
# --- constants ---
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
GREY = (128, 128, 128)
#PI = 3.1415
# --- main ----
pygame.init()
screen = pygame.display.set_mode((800,600))
# - generate PIL image with transparent background -
pil_size = 300
pil_image = Image.new("RGBA", (pil_size, pil_size))
pil_draw = ImageDraw.Draw(pil_image)
#pil_draw.arc((0, 0, pil_size-1, pil_size-1), 0, 270, fill=RED)
pil_draw.pieslice((0, 0, pil_size-1, pil_size-1), 330, 0, fill=GREY)
# - convert into PyGame image -
mode = pil_image.mode
size = pil_image.size
data = pil_image.tobytes()
image = pygame.image.fromstring(data, size, mode)
image_rect = image.get_rect(center=screen.get_rect().center)
# - mainloop -
clock = pygame.time.Clock()
running = True
while running:
clock.tick(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
screen.fill(WHITE)
#pygame.draw.arc(screen, BLACK, (300, 200, 200, 200), 0, PI/2, 1)
#pygame.gfxdraw.pie(screen, 400, 300, 100, 0, 90, RED)
#pygame.gfxdraw.arc(screen, 400, 300, 100, 90, 180, GREEN)
screen.blit(image, image_rect) # <- display image
pygame.display.flip()
# - end -
pygame.quit()
Result:
GitHub: furas/python-examples/pygame/pillow-image-pieslice
Upvotes: 3