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

如何利用SFML顶点数组结合sf::TriangleFan绘制圆形?

使用SFML的sf::TriangleFan绘制圆形的实现步骤

核心思路

sf::TriangleFan 是SFML中适配扇形/圆形绘制的顶点数组模式——它以第一个顶点为中心,后续每个顶点会自动与前一个顶点、中心组成三角形,刚好满足圆形的填充需求。

具体实现步骤

  1. 初始化顶点数组
    创建类型为 sf::TriangleFan 的顶点数组,作为存储圆形顶点的容器。

  2. 添加圆心顶点
    将圆形的中心点作为顶点数组的第一个元素,所有后续三角形都会以此为公共顶点。

  3. 计算圆周顶点坐标
    通过三角函数计算圆周上的顶点位置:

    • 用 2 * M_PI(完整圆周弧度)除以分段数,得到每段的角度增量
    • 遍历每个分段,用 cos(角度) 和 sin(角度) 计算对应点的x、y坐标(SFML默认坐标系y轴向下,无需额外调整)
  4. 填充顶点数组并闭合圆形
    将所有圆周顶点加入数组,最后再添加一次第一个圆周顶点,避免圆形边缘出现缺口。

完整代码示例

#include <SFML/Graphics.hpp>
#include <cmath> // 用于三角函数和M_PI

sf::VertexArray createCircle(sf::Vector2f center, float radius, int segments) {
    sf::VertexArray circle(sf::TriangleFan);
    
    // 添加圆心
    circle.append(sf::Vertex(center, sf::Color::Red));
    
    // 计算每段的角度增量
    float angleStep = 2 * M_PI / segments;
    
    // 生成圆周顶点,最后重复第一个点闭合圆形
    for (int i = 0; i <= segments; ++i) {
        float currentAngle = i * angleStep;
        float x = center.x + radius * std::cos(currentAngle);
        float y = center.y + radius * std::sin(currentAngle);
        circle.append(sf::Vertex(sf::Vector2f(x, y), sf::Color::Red));
    }
    
    return circle;
}

int main() {
    sf::RenderWindow window(sf::VideoMode(800, 600), "Circle via TriangleFan");
    // 创建圆心在(400,300)、半径150、30段的圆形(30段足够平滑)
    sf::VertexArray circle = createCircle(sf::Vector2f(400, 300), 150, 30);

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear(sf::Color::White);
        window.draw(circle);
        window.display();
    }
    return 0;
}

关键注意事项

  • 分段数选择:20-30段就能得到足够平滑的圆形,过少会呈现多边形形态,过多则会浪费性能。
  • 颜色自定义:可以给不同顶点设置不同颜色,实现渐变效果(比如圆心用sf::Color::Pink,外围用sf::Color::Red)。
  • 顶点数组复用:创建好的顶点数组可多次绘制,无需每次重新生成,提升运行效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:31:00