macOS路径NSBezierPath
macOS路径NSBezierPath

macOS路径NSBezierPath

NSBezierPath 是 macOS(AppKit 框架)中用于构建和绘制二维路径(图形、线条、曲线等)的类,是 macOS 上的高层 API,类似于 iOS 上的 UIBezierPath。

NSBezierPath 是 macOS 上用于描述和绘制矢量路径的类,具备路径构建、绘制、样式设置等功能。

它是一个可变对象,可以添加线、弧、曲线等路径,设置线宽、描边、填充颜色,甚至用它来做点击检测。

初始化方法

init()
init(ovalIn: NSRect)
init(rect: NSRect)
init(roundedRect: NSRect, xRadius: CGFloat, yRadius: CGFloat)

例如:

let path = NSBezierPath(roundedRect: bounds.insetBy(dx: 10, dy: 10), xRadius: 10, yRadius: 10)

常用方法

一、路径构建

1、move(to:):移动画笔起点;

2、line(to:):添加直线段;

3、curve(to:controlPoint1:controlPoint2:):添加三次 Bézier 曲线;

4、close():闭合当前子路径;

5、appendRect(_:):添加矩形路径;

6、appendOval(in:):添加椭圆或圆形路径;

7、appendArc(withCenter:radius:startAngle:endAngle:clockwise:):添加圆弧;

8、append(_:):合并另一个 NSBezierPath;

9、removeAllPoints():清除所有路径。

二、绘图方法

1、stroke():描边当前路径;

2、fill():填充路径内部区域;

3、stroke(with:alpha:):使用指定混合模式描边;

4、fill(with:alpha:):使用指定混合模式填充。

三、样式属性

1、lineWidth:CGFloat类型,线宽;

2、lineCapStyle:枚举.butt, .round, .square,线帽样式(线段末端);

3、lineJoinStyle:枚举.miter, .round, .bevel,线连接方式;

4、miterLimit:CGFloat类型,斜接限制;

5、flatness:CGFloat类型,曲线平滑度(影响精度);

6、windingRule:枚举.evenOdd, .nonZero,填充规则(是否包含某点);

7、usesEvenOddFillRule:Bool类型,是否使用奇偶填充规则(快捷方式);

8、defaultLineWidth:CGFloat (class var)类型,默认线宽。

四、查询与转换

1、isEmpty:Bool类型,路径是否为空;

2、bounds:NSRect类型,包含整个路径的矩形区域;

3、currentPoint:NSPoint类型,当前绘图点;

4、contains(_:):Bool类型,是否包含某点(命中测试);

5、elementCount:Int类型,路径元素数量;

6、element(at:associatedPoints:):(type, points)类型,获取某个路径元素及控制点;

7、cgPath:CGPath类型,转换为 Core Graphics 路径(14+);

8、copy():NSBezierPath类型,克隆路径。

五、路径元素

1、.moveTo:移动到新点;

2、.lineTo:添加线段;

3、.curveTo:添加三次贝塞尔曲线;

4、.closePath:闭合路径。

使用示例

1、绘制红色圆角矩形

override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)
    
    let path = NSBezierPath(roundedRect: bounds.insetBy(dx: 10, dy: 10), xRadius: 10, yRadius: 10)
    NSColor.red.setFill()
    path.fill()
}

1)roundedRect:添加圆角矩形路径;

2)NSColor.red.setFill():设置当前填充颜色;

3)path.fill():执行填充绘制。

2、将NSBezierPath转换为CGPath(用于CAShapeLayer)

let bezierPath = NSBezierPath()
bezierPath.move(to: .zero)
bezierPath.line(to: CGPoint(x: 100, y: 100))

let shapeLayer = CAShapeLayer()
shapeLayer.path = bezierPath.cgPath  // macOS 14+ 支持

需要注意的是,cgPath属性只支持macOS 14+版本。

总结

NSBezierPath 是 macOS 上的矢量路径构建类,既能创建路径,也能直接绘制,是高层、易用、功能丰富的绘图 API。

在macOS的draw(_:)方法中手动绘图时,才会用到NSBezierPath:

override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)
    NSColor.systemBlue.setStroke()
    let path = NSBezierPath(rect: CGRect(x: 100, y: 100, width: 100, height: 100))
    path.lineWidth = 3
    path.stroke()
}

这种适合静态内容、不频繁变化的场景。

如果需要动态更新选区、支持实时渲染,那么应该使用CAShapeLayer

相关文章

1、Core Animation绘制图像路径CAShapeLayer:https://fangjunyu.com/2025/07/31/core-animation%e7%bb%98%e5%88%b6%e5%9b%be%e5%83%8f%e8%b7%af%e5%be%84cashapelayer/

   

如果您认为这篇文章给您带来了帮助,您可以在此通过支付宝或者微信打赏网站开发者。

欢迎加入我们的 微信交流群QQ交流群,交流更多精彩内容!
微信交流群二维码 QQ交流群二维码

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注