我有一个我想绘制的绘图区域和我不想绘制的边界。目前,如果鼠标位置(m_x 和 m_y)在边界的圆圈半径内,我让程序绘制圆圈,然后重绘矩形,该矩形切掉圆圈交叉的部分。必须有一种更智能、更有效的方法来仅绘制圆圈中边界内的部分。
if event.type == pygame.MOUSEBUTTONDOWN or pygame.MOUSEMOTION and mouse_pressed[0] == 1:
if m_x < draw_areax-brush_size and m_y < draw_areay-brush_size:
circle = pygame.draw.circle(screen,brush_colour,(m_x,m_y),brush_size)
else:
circle = pygame.draw.circle(screen,brush_colour,(m_x,m_y),brush_size)
reloadareas()
最佳答案
pygame.draw
的文档说:
All the drawing functions respect the clip area for the Surface, and will be constrained to that area.
因此,如果您只想绘制某个矩形区域内的圆圈部分,请通过调用 pygame.Surface.set_clip
设置一个剪辑区域。 , 绘制圆圈,然后移除剪辑区域。假设您通常在屏幕上没有有效的剪辑区域,那么您可以这样编程:
clip_area = pygame.Rect(0, 0, draw_areax, draw_areay)
screen.set_clip(clip_area)
pygame.draw.circle(...)
screen.set_clip(None) # clear the clip area
这是一个例子:
from pygame import *
init()
screen = display.set_mode((640, 480))
# Yellow circle drawn without clipping
draw.circle(screen, Color('yellow'), (150, 120), 60)
# Orange circle drawn with clipping
clip = Rect((100, 100, 200, 100))
screen.set_clip(clip)
draw.circle(screen, Color('orange'), (150, 120), 60)
screen.set_clip(None)
# Outline the clip rectangle in black
draw.rect(screen, Color('black'), clip, 1)
display.flip()
如果您使用剪辑矩形进行大量绘图,那么您可能希望将剪辑矩形的设置和取消设置封装在 context manager 中。 ,也许像这样,使用 contextlib.contextmanager
:
from contextlib import contextmanager
@contextmanager
def clipped(surface, clip_rect):
old_clip_rect = surface.get_clip()
surface.set_clip(clip_rect)
try:
yield
finally:
surface.set_clip(old_clip_rect)
然后我的例子可以这样写:
# Orange circle drawn with clipping
clip = Rect((100, 100, 200, 100))
with clipped(screen, clip):
draw.circle(screen, Color('orange'), (150, 120), 60)
关于python - 我如何限制pygame.draw.circle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29496832/