LoginSignup
0
0

More than 5 years have passed since last update.

Swift:CGPathをNSBezierPathに変換する

Posted at

背景

NSBezierPathをCGPathに一旦変更して利用した後、再びNSBezierPathに戻したい場合があったため、方法を探りました。

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

import Cocoa

extension CGPath {

    public var nsBezierPath: NSBezierPath {
        let path = NSBezierPath()
        self.applyWithBlock { (element) in
            switch element.pointee.type {
            case CGPathElementType.moveToPoint:
                path.move(to: NSPoint(x: element.pointee.points[0].x, y: element.pointee.points[0].y))
            case CGPathElementType.addLineToPoint:
                path.line(to: NSPoint(x: element.pointee.points[0].x, y: element.pointee.points[0].y))
            case CGPathElementType.addCurveToPoint:
                path.curve(to: NSPoint(x: element.pointee.points[2].x, y: element.pointee.points[2].y),
                           controlPoint1: NSPoint(x: element.pointee.points[0].x, y: element.pointee.points[0].y),
                           controlPoint2: NSPoint(x: element.pointee.points[1].x, y: element.pointee.points[1].y))
            case CGPathElementType.addQuadCurveToPoint:
                path.curve(to: NSPoint(x: element.pointee.points[1].x, y: element.pointee.points[1].y),
                           controlPoint1: NSPoint(x: element.pointee.points[0].x, y: element.pointee.points[0].y),
                           controlPoint2: NSPoint(x: element.pointee.points[0].x, y: element.pointee.points[0].y))
            case CGPathElementType.closeSubpath:
                path.close()
            }
        }
        return path
    }

}

使い方

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

0
0
0

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
0
0