enum PathElement: Codable, Equatable {
case moveToPoint(CGPoint)
case addLineToPoint(CGPoint)
case addQuadCurveToPoint(controlPoint: CGPoint, endPoint: CGPoint)
case addCurveToPoint(controlPoint1: CGPoint, controlPoint2: CGPoint, endPoint: CGPoint)
case closeSubpath
}
extension CGPath {
static func pathFromPathElements(_ pathElements: [PathElement]) -> CGPath {
let path = CGMutablePath()
for pathElement in pathElements {
switch pathElement {
case .moveToPoint(let point):
path.move(to: point)
case .addLineToPoint(let point):
path.addLine(to: point)
case .addQuadCurveToPoint(let controlPoint, let endPoint):
path.addQuadCurve(to: endPoint, control: controlPoint)
case .addCurveToPoint(let controlPoint1, let controlPoint2, let endPoint):
path.addCurve(to: endPoint, control1: controlPoint1, control2: controlPoint2)
case .closeSubpath:
path.closeSubpath()
}
}
return path
}
func pathElements() -> [PathElement] {
var result = [PathElement]()
applyWithBlock { elementPointer in
let element = elementPointer.pointee
switch element.type {
case .moveToPoint:
let points = Array(UnsafeBufferPointer(start: element.points, count: 1))
let el = PathElement.moveToPoint(points[0])
result.append(el)
case .addLineToPoint:
let points = Array(UnsafeBufferPointer(start: element.points, count: 1))
let el = PathElement.addLineToPoint(points[0])
result.append(el)
case .addQuadCurveToPoint:
let points = Array(UnsafeBufferPointer(start: element.points, count: 2))
let el = PathElement.addQuadCurveToPoint(
controlPoint: points[0], endPoint: points[1])
result.append(el)
case .addCurveToPoint:
let points = Array(UnsafeBufferPointer(start: element.points, count: 3))
let el = PathElement.addCurveToPoint(
controlPoint1: points[0], controlPoint2: points[1], endPoint: points[2])
result.append(el)
case .closeSubpath:
result.append(.closeSubpath)
@unknown default:
fatalError()
}
}
return result
}
}
3条答案
按热度按时间dwthyt8l1#
您可以将其序列化为数据(以 NSData 示例的形式),因为 UIBezierPath 符合 NSCoding(即
字符串
另一个选项可能是转换为SVG或从SVG转换并保存。
xxhby3vn2#
您可以保存
UIBezierPath
的所有控制点,而不是直接保存路径。e7arh2l63#
您可以通过定义路径模型并使用Codable来序列化/并行化
UIBezierPath
。虽然将lineWidth
或lineCapStyle
这样的属性设置为Codable
很简单,但路径元素(存储在UIBezierPath.cgPath
中)的代码要复杂得多。然而,这里是一个起点:字符串