LoginSignup
3

More than 5 years have passed since last update.

Swift:NSBezierPathをCGPathに変換する

Last updated at Posted at 2018-07-11

背景

画像処理を行おうとして、NSBezierPathをCGPathに一旦変更する必要があった。
意外と日本語のリファレンスがなかったため忘備録としてまとめる。

ソースコード(2018/7/11 Swift4対応版)

import Cocoa

extension NSBezierPath {

    public var cgPath: CGPath {
        let path: CGMutablePath = CGMutablePath()
        var points = [NSPoint](repeating: NSPoint.zero, count: 3)
        for i in (0 ..< self.elementCount) {
            switch self.element(at: i, associatedPoints: &points) {
            case .moveToBezierPathElement:
                path.move(to: CGPoint(x: points[0].x, y: points[0].y))
            case .lineToBezierPathElement:
                path.addLine(to: CGPoint(x: points[0].x, y: points[0].y))
            case .curveToBezierPathElement:
                path.addCurve(to: CGPoint(x: points[2].x, y: points[2].y),
                              control1: CGPoint(x: points[0].x, y: points[0].y),
                              control2: CGPoint(x: points[1].x, y: points[1].y))
            case .closePathBezierPathElement:
                path.closeSubpath()
            }
        }
        return path
    }

}

使い方

上のソースコードをPathExtension.swiftなど適当な名前をつけてプロジェクトファイルに突っ込めば準備OK!
あとはNSBezierPathのパス生成後にpath.cgPathとすればCGPathが取得できる。

備考

UIBezierPathも同様にできる模様

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3