Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions Source/utils/CGMappings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,52 @@ public extension Node {
}

}

extension CGPath {

public func toMacaw() -> Path {

func createPathSegment(type: PathSegmentType, points: UnsafeMutablePointer<CGPoint>, count: Int) -> PathSegment {

var data = [Double]()
for index in 0..<count {
let point = points[index]
data.append(contentsOf: [Double(point.x), Double(point.y)])
}
return PathSegment(type: type, data: data)
}

var segments = [PathSegment]()
self.forEach(body: { (element: CGPathElement) in

let segment: PathSegment
switch element.type {
case .moveToPoint:
segment = createPathSegment(type: .M, points: element.points, count: 1)
case .addLineToPoint:
segment = createPathSegment(type: .L, points: element.points, count: 1)
case .addQuadCurveToPoint:
segment = createPathSegment(type: .Q, points: element.points, count: 2)
case .addCurveToPoint:
segment = createPathSegment(type: .C, points: element.points, count: 3)
case .closeSubpath:
segment = PathSegment(type: .z)
@unknown default:
fatalError()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be great to add message to fatal error, like "Unknown segment type: " + element.type

}
segments.append(segment)
})

return Path(segments: segments, fillRule: .nonzero)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting that CGPath doesn't have fill rule, but UIBezierPath have. In this case we need to support UIBezierPath.toMacaw() as well which will handle fill rule.

}

private func forEach( body: @escaping @convention(block) (CGPathElement) -> Void) {
typealias Body = @convention(block) (CGPathElement) -> Void
func callback(info: UnsafeMutableRawPointer?, element: UnsafePointer<CGPathElement>) {
let body = unsafeBitCast(info, to: Body.self)
body(element.pointee)
}
let unsafeBody = unsafeBitCast(body, to: UnsafeMutableRawPointer.self)
self.apply(info: unsafeBody, function: callback)
}
}