python - 我如何限制pygame.draw.circle?

标签 python pygame

我有一个我想绘制的绘图区域和我不想绘制的边界。目前,如果鼠标位置(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/

相关文章:

python - Pylint 无法在 mercurial 预提交 Hook 上加载插件

python - 管道各个部分中的 ColumnTransformer 表现不佳

python - 属性错误: 'Mob' object has no attribute '_Sprite__g'

python - 解释按下的键

python - pygame 项目无法运行 : "pygame.error: No available video device"

python - 滚动相机

Python - Pygame For android 错误

python - CNN模型分类错误: logits and labels must be broadcastable: logits_size=[32, 10] labels_size=[32,13]

Python 3 从互联网广播流中获取歌曲名称

Python:在读取文件并对一行中的单词进行计数时,我想将 ""或 ' ' 之间的单词计算为一个单词