Eugene Kartashev
Eugene Kartashev

Reputation: 173

How to fill my figure with a color in pygame?

I've got a code which allows me to draw different curves with the help of the mouse. My task is to fill this drawn curve with a color. I know for sure that the curve is closed.

My current code:

import pygame as py
import sys

py.init()
White = (255,255,255)
Black = (0,0,0)
clock = py.time.Clock()
H = 400
W = 600
sc = py.display.set_mode((W,H))
sc.fill(White)
py.display.set_caption('Curve drawing')
py.display.update()
draw = False

while 1:
    for i in py.event.get():
        if i.type == py.QUIT:
            py.image.save(sc,r'C:/Users/Xiaomi' + '/temporary.png')
            py.quit()
            sys.exit()
        elif i.type == py.MOUSEBUTTONDOWN:
            if i.button == 1:
                draw = True
            elif i.button == 2:
                sc.fill(White)
                py.display.update()
        elif i.type == py.MOUSEBUTTONUP:
            if i.button == 1:
                draw = False
    if draw == True:
        py.draw.circle(sc,Black,i.pos,7)
        py.display.update()

Can anybody show me how to do this?

Upvotes: 4

Views: 1470

Answers (1)

Kingsley
Kingsley

Reputation: 14906

You could use PyGame polygon drawing function to create a filled area bounded by all the mouse points. Ref: https://www.pygame.org/docs/ref/draw.html#pygame.draw.polygon

So instead of drawing a circle at each point, keep adding the mouse position to a list of co-ordinates as the mouse moves. When the button is released, draw a filled polygon around all these points.

fill_coords = []    # points to make filled polygon

while 1:
    for i in py.event.get():
        if i.type == py.QUIT:
            py.image.save(sc,r'C:/Users/Xiaomi' + '/temporary.png')
            py.quit()
            sys.exit()

        elif i.type == py.MOUSEBUTTONDOWN:
            if i.button == 1:
                draw = True
                fill_coords = []                              # restart the polygon
            elif i.button == 2:
                sc.fill(White)
                py.display.update()

        elif i.type == py.MOUSEBUTTONUP:
            if i.button == 1:
                draw = False
                pygame.draw.polygon( sc, Black, fill_coords ) # filled polygon

        elif i.type == pygame.MOUSEMOTION:                    # when the mouse moves
            if ( draw ):
                fill_coords.append( i.pos )                   # remember co-ordinate
    mouse_position = pygame.mouse.get_pos()
    if draw == True:
        py.draw.circle(sc,Black,i.pos,7)
        py.display.update()

Upvotes: 4

Related Questions