将CGPathRef转换为NSBezierPath

问题描述 投票:2回答:1

在Apple文档中,他们为您提供了如何将NSBezierPath转换为CGPathRef的代码。我需要转换其他方式,从CGPathRef到NSBezierPath。 UIBezierPath有一个名为cgPath的属性,所以如果我在iPhone上工作不会有问题,但我正在研究MacOS。

这一定是一个老问题,我肯定会在互联网上找到答案,但没有运气。可能是我错过了什么。任何帮助赞赏。

macos nsbezierpath cgpathref
1个回答
2
投票

老问题,但我相信这对其他人仍然有用。 (你没有指定Objective-C或Swift;这是一个Objective-C答案。)

你可以使用CGPathRefNSBezierPath转换为CGPathApply(),并使用回调将CGPathRef点转换为NSBezierPath点。唯一棘手的部分是从CGPathRef的二次曲线到NSBezierPath的三次曲线的对话,但there's an equation for that

任何二次样条可以表示为立方(其中立方项为零)。立方体的终点与二次方的终点相同。

 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 CGPathCallback(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, CGPathCallback);
    return bezierPath;
}
@end

这样称呼:

//...get cgPath (CGPathRef) from somewhere
NSBezierPath *bezierPath = [NSBezierPath JNS_bezierPathWithCGPath:cgPath];
© www.soinside.com 2019 - 2024. All rights reserved.