C
C
Clay2020-08-22 23:51:11
Python
Clay, 2020-08-22 23:51:11

How to fill a shape in pygame?

Hello, I have recently started learning the pygame module and have come across the following problem. There is code that I can use to draw shapes with the mouse and then save that surface as a picture. The problem is - how do I fill the area inside my shape with some color? I know for sure that the curve must be closed.

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()


Here is an example of shapes.
5f41852e7694f864755059.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan, 2020-08-23
@Pushunter

In pygame, when drawing various shapes, the fill is determined depending on the presence of the line width parameter.
That is, in your case:
py.draw.circle(sc,Black,i.pos,7)
the last parameter 7 specifies the width of the line, so no shading occurs.
If this option is removed, the entire circle will be filled with black.
If you need to define both the fill and the color of the outline with different colors, then you need to draw the shape twice, first with the fill, and then with the outline line. For example like this:

py.draw.circle(sc,Green,i.pos)
py.draw.circle(sc,Red,i.pos,7)

In this case, you get a circle filled with green, and a red outline.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question