老问题,但我相信这对其他人仍然有帮助。 (您没有指定 Objective-C 或 Swift;这是 Objective-C 答案。)
您可以转换一个CGPathRef
to an NSBezierPath
using CGPathApply()
使用应用程序函数回调来翻译CGPathRef
指着NSBezierPath
点。唯一棘手的部分是从CGPathRef
的二次曲线为NSBezierPath
的三次曲线但是有一个方程式 http://fontforge.github.io/bezier.html:
任何二次样条都可以表示为三次样条(其中三次项为零)。三次方程的端点与二次方程的端点相同。
CP0 = QP0
CP3 = QP2
三次方的两个控制点是:
CP1 = QP0 + 2/3 * (QP1-QP0)
CP2 = QP2 + 2/3 * (QP1-QP2)
...由于舍入而引入了轻微的误差,但通常不明显。
使用上面的等式,这是一个NSBezierPath
转换自的类别CGPathRef
:
NSBezierPath+BezierPathWithCGPath.h
@interface NSBezierPath (BezierPathWithCGPath)
+ (NSBezierPath *)JNS_bezierPathWithCGPath:(CGPathRef)cgPath; //prefixed as Apple may add bezierPathWithCGPath: method someday
@end
NSBezierPath+BezierPathWithCGPath.m
static void CGPathToBezierPathApplierFunction(void *info, const CGPathElement *element) {
NSBezierPath *bezierPath = (__bridge NSBezierPath *)info;
CGPoint *points = element->points;
switch(element->type) {
case kCGPathElementMoveToPoint: [bezierPath moveToPoint:points[0]]; break;
case kCGPathElementAddLineToPoint: [bezierPath lineToPoint:points[0]]; break;
case kCGPathElementAddQuadCurveToPoint: {
NSPoint qp0 = bezierPath.currentPoint, qp1 = points[0], qp2 = points[1], cp1, cp2;
CGFloat m = (2.0 / 3.0);
cp1.x = (qp0.x + ((qp1.x - qp0.x) * m));
cp1.y = (qp0.y + ((qp1.y - qp0.y) * m));
cp2.x = (qp2.x + ((qp1.x - qp2.x) * m));
cp2.y = (qp2.y + ((qp1.y - qp2.y) * m));
[bezierPath curveToPoint:qp2 controlPoint1:cp1 controlPoint2:cp2];
break;
}
case kCGPathElementAddCurveToPoint: [bezierPath curveToPoint:points[2] controlPoint1:points[0] controlPoint2:points[1]]; break;
case kCGPathElementCloseSubpath: [bezierPath closePath]; break;
}
}
@implementation NSBezierPath (BezierPathWithCGPath)
+ (NSBezierPath *)JNS_bezierPathWithCGPath:(CGPathRef)cgPath {
NSBezierPath *bezierPath = [NSBezierPath bezierPath];
CGPathApply(cgPath, (__bridge void *)bezierPath, CGPathToBezierPathApplierFunction);
return bezierPath;
}
@end
像这样调用:
//...get cgPath (CGPathRef) from somewhere
NSBezierPath *bezierPath = [NSBezierPath JNS_bezierPathWithCGPath:cgPath];