gpt4 book ai didi

python - 如何在pygame中用颜色填充我的图形?

转载 作者:行者123 更新时间:2023-12-03 23:04:23 26 4
gpt4 key购买 nike

我有一个代码,它允许我在鼠标的帮助下绘制不同的曲线。我的任务是用颜色填充这条绘制的曲线。我确信曲线是闭合的。
我目前的代码:

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()
谁能告诉我如何做到这一点?

最佳答案

您可以使用 PyGame 多边形绘制功能创建一个由所有鼠标点包围的填充区域。引用:https://www.pygame.org/docs/ref/draw.html#pygame.draw.polygon
因此,不要在每个点画一个圆,而是在鼠标移动时将鼠标位置添加到坐标列表中。释放按钮后,围绕所有这些点绘制一个填充的多边形。

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

关于python - 如何在pygame中用颜色填充我的图形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63541054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com