Mac 开发之获取 NSBezierPath 的 CGPath

比如在 CGContextAddPath(ctx, 需要用到path.CGPath);
然而 在 NSBezierPath 中并没有 path.CGPath

修改为:

CGContextAddPath(ctx, [self CGPathFromPath:path]);

转换方法:CGPathFromPath 如下

- (CGMutablePathRef)CGPathFromPath:(NSBezierPath *)path
{
    CGMutablePathRef cgPath = CGPathCreateMutable();
    NSInteger n = [path elementCount];
    
    for (NSInteger i = 0; i < n; i++) {
        NSPoint ps[3];
        switch ([path elementAtIndex:i associatedPoints:ps]) {
            case NSMoveToBezierPathElement: {
                CGPathMoveToPoint(cgPath, NULL, ps[0].x, ps[0].y);
                break;
            }
            case NSLineToBezierPathElement: {
                CGPathAddLineToPoint(cgPath, NULL, ps[0].x, ps[0].y);
                break;
            }
            case NSCurveToBezierPathElement: {
                CGPathAddCurveToPoint(cgPath, NULL, ps[0].x, ps[0].y, ps[1].x, ps[1].y, ps[2].x, ps[2].y);
                break;
            }
            case NSClosePathBezierPathElement: {
                CGPathCloseSubpath(cgPath);
                break;
            }
            default: NSAssert(0, @"Invalid NSBezierPathElement");
        }
    }
    return cgPath;
}

最后笔者换了实现方法 ,此方法未验证,不过该方法得来不易,特此记录。

你可能感兴趣的:(Mac 开发之获取 NSBezierPath 的 CGPath)