Chapter 26 · 基础图元

椭圆

绘制椭圆——圆形的泛化形式,用独立的 X/Y 半径控制形状,适用于阴影、轨道、按钮等。

26

API 速查

函数说明
void xgeShapeEllipseFill(float fX, float fY, float fRadiusX, float fRadiusY, uint32_t iColor)填充椭圆
void xgeShapeEllipseFillPx(float fX, float fY, float fRadiusX, float fRadiusY, uint32_t iColor)填充椭圆(像素坐标)
void xgeShapeEllipseStroke(float fX, float fY, float fRadiusX, float fRadiusY, float fWidth, uint32_t iColor)描边椭圆
void xgeShapeEllipseStrokePx(float fX, float fY, float fRadiusX, float fRadiusY, float fWidth, uint32_t iColor)描边椭圆(像素坐标)

编译本章示例

gcc -O2 -I. -o ch26.exe ch26_main.c build\xge.lib -lm -lws2_32 -liphlpapi -lgdi32 -luser32 -lshell32 -lopengl32 -lole32 -lwinmm -lavrt
.\ch26.exe

示例 1:基本椭圆

// 横向椭圆:X 半径 150,Y 半径 80
xgeShapeEllipseFill(400, 300, 150.0f, 80.0f, 0x4FD8C2FF);

// 纵向椭圆
xgeShapeEllipseFill(200, 300, 50.0f, 120.0f, 0xFFB454FF);

// 描边椭圆轨道
xgeShapeEllipseStroke(400, 300, 250.0f, 120.0f, 2.0f, 0x6DB3F260);

示例 2:地面阴影

// 角色脚下的椭圆阴影
float playerX = 400, groundY = 480;
xgeShapeEllipseFill(playerX, groundY, 40.0f, 12.0f, 0x00000060);

// 角色(圆形)
xgeShapeCircleFill(playerX, groundY - 60, 30.0f, 0xFF6B5EFF);

示例 3:行星轨道动画

double t = xgeTimer();
float cx = 400, cy = 300;
float rx = 200, ry = 100;

// 绘制轨道
xgeShapeEllipseStroke(cx, cy, rx, ry, 1.0f, 0x333333FF);

// 行星沿椭圆轨道运动
float angle = (float)(t * 1.5);
float px = cx + rx * cosf(angle);
float py = cy + ry * sinf(angle);
xgeShapeCircleFill(px, py, 12.0f, 0xFFB454FF);

完整代码

将以下代码保存为 ch26_main.c,编译后运行即可看到椭圆绘制效果:

#include "xge.h"

static int onFrame(void* pUser) {
    (void)pUser;
    xgeClear(0x081114FF);

    // 横向椭圆(宽 > 高)
    xgeShapeEllipseFill(250, 200, 150, 80, 0x4FD8C2FF);

    // 纵向椭圆(高 > 宽)
    xgeShapeEllipseFill(550, 200, 70, 130, 0xFFB454FF);

    // 描边椭圆
    xgeShapeEllipseFill(400, 430, 180, 100, 3.0f, 0xFF6B5EFF);

    return XGE_OK;
}

int main(void) {
    xge_desc_t d = {0};
    d.iWidth  = 800;
    d.iHeight = 600;
    d.sTitle  = "ch26 - Ellipse";
    d.iFlags  = XGE_INIT_VSYNC;
    xgeInit(&d);
    xgeRun(onFrame, NULL);
    xgeUnit();
    return 0;
}

代码讲解

  • xgeShapeEllipseFill(cx, cy, rx, ry, color) 绘制实心椭圆,rx/ry 为横纵半径。
  • xgeShapeEllipseFill(cx, cy, rx, ry, width, color) 绘制椭圆描边。
  • 当 rx == ry 时椭圆退化为圆形。
  • 椭圆常用于绘制阴影、光晕、运动场等场景。

要点与陷阱

  • RadiusX = RadiusY 时就是圆:椭圆是圆的超集。
  • 轴对齐:椭圆的长短轴始终沿 X/Y 方向。旋转椭圆需要用 ShapeEx + Transform(第 61 章)。
  • 描边均匀:线宽沿椭圆法线方向均匀分布,不会在曲率大的地方变细。
  • 零半径:任一半径为 0 时退化为线段或不绘制。

进阶练习

  1. 绘制多个同心椭圆,形成"隧道"透视效果。
  2. 实现椭圆碰撞检测:判断点是否在椭圆内(x²/a² + y²/b² ≤ 1)。
  3. 用椭圆弧(结合第 24 章思路)绘制一个椭圆进度环。
椭圆效果
图:椭圆渲染效果