CGPath 是 Core Graphics 框架中的一个不可变路径对象(immutable path),用于定义 2D 图形中的几何形状,如线段、曲线和路径轮廓。
通常使用CGMutablePath创建路径,构建完成后转换为CGPath使用。
例如,创建一个矩形路径:
let mutablePath = CGMutablePath()
mutablePath.addRect(CGRect(x: 20, y: 20, width: 100, height: 100))

可以将 path 赋值给 CAShapeLayer.path,或者在 draw(_:) 方法中使用。
let mutablePath = CGMutablePath()
mutablePath.addRect(CGRect(x: 0, y: 0, width: 100, height: 100))
var shapeLayer = CAShapeLayer()
shapeLayer.path = mutablePath // 赋值path
shapeLayer.fillColor = NSColor.blue.cgColor
shapeLayer.strokeColor = NSColor.systemBlue.cgColor

CGPath使用场景
1、CAShapeLayer.path:用来显示任意路径图形;
2、draw(_:) 方法中手动绘图;
3、与物理引擎、动画、点击检测结合使用;
4、用于遮罩(mask)、裁剪区域(clip path)。
总结
CGPath 是一个用于定义矢量图形的不可变路径对象,可配合 Core Graphics 或图层系统渲染图形,是绘制曲线和图形的基础。
CGPath和CGMutablePath的关系,CGMutablePath是一个绘画的彩笔,当绘画完成后,就需要保存到相框中(CGPath)。
在绘制路径时,使用CGMutablePath绘制,绘制路径后,再转换为CGPath使用。
因此,CGPath是不可变的,CGMutablePath是CGPath的子类,所以也可以当作CGPath使用。
相关文章
1、Core Graphics路径CGMutablePath:https://fangjunyu.com/2025/08/01/core-graphics%e8%b7%af%e5%be%84cgmutablepath/
2、Apple二维图像绘制框架Core Graphics:https://fangjunyu.com/2024/12/16/apple%e4%ba%8c%e7%bb%b4%e5%9b%be%e5%83%8f%e7%bb%98%e5%88%b6%e6%a1%86%e6%9e%b6core-graphics/