You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pyglet中绘制圆弧/空心扇形?

在Pyglet中绘制空心扇形(带圆心连线的圆弧)

你需要的效果如下:
空心扇形效果

要实现这种空心扇形(圆弧+连接圆心的两条线段),Pyglet原生的Sector仅支持填充样式,Arc只绘制圆弧,都无法直接满足需求,可通过组合现有API自定义实现。

实现方案

自定义一个HollowSector类,封装圆弧和两条线段的绘制逻辑:

import pyglet
from pyglet.math import Vec2
from pyglet.shapes import Arc
import math

class HollowSector:
    def __init__(self, x, y, radius, segments, angle, start_angle=0, color=(255, 255, 255)):
        self.x = x
        self.y = y
        self.radius = radius
        self.segments = segments
        self.angle = angle
        self.start_angle = start_angle
        self.color = color
        
        # 计算圆弧两端点的坐标
        end_angle = start_angle + angle
        self.start_point = Vec2(
            x + radius * math.cos(math.radians(start_angle)),
            y + radius * math.sin(math.radians(start_angle))
        )
        self.end_point = Vec2(
            x + radius * math.cos(math.radians(end_angle)),
            y + radius * math.sin(math.radians(end_angle))
        )
        
        # 创建圆弧对象
        self.arc = Arc(
            x, y, radius, segments, 
            math.radians(angle), math.radians(start_angle), 
            color=color
        )
    
    def draw(self):
        # 绘制圆弧
        self.arc.draw()
        # 绘制圆心到圆弧起点的线段
        pyglet.graphics.draw(2, pyglet.gl.GL_LINES,
                            ('v2f', (self.x, self.y, self.start_point.x, self.start_point.y)),
                            ('c3B', self.color * 2))
        # 绘制圆心到圆弧终点的线段
        pyglet.graphics.draw(2, pyglet.gl.GL_LINES,
                            ('v2f', (self.x, self.y, self.end_point.x, self.end_point.y)),
                            ('c3B', self.color * 2))

# 使用示例
window = pyglet.window.Window(width=400, height=400)

@window.event
def on_draw():
    window.clear()
    # 绘制一个22.5度的红色空心扇形
    hollow_sector = HollowSector(
        x=200, y=200, radius=150, 
        segments=200, angle=22.5, 
        color=(255, 0, 0)
    )
    hollow_sector.draw()

pyglet.app.run()

安装问题说明

在Windows 10 + Python 3.10环境下,执行pip install pyglet==2.0.10会安装损坏的包,导致Arc无法正常绘制。解决方法是从源码安装Pyglet:

  • 克隆仓库:git clone https://github.com/pyglet/pyglet.git
  • 进入仓库目录:cd pyglet
  • 执行本地安装:pip install .

内容的提问来源于stack exchange,提问作者mister_kanister

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 03:15:16