将 NSMutableArray 转换为 CGPoint 数组

convert NSMutableArray to CGPoint Array

典型的答案是“您可以将其转换为 nsvalue,然后使用 [element CGPointValue]; 但在我的例子中,我需要生成 CGPoint 类型的数组,因为我在下面的内置函数中需要它:

static CGPathRef createClosedPathWithPoints(const CGPoint *points, size_t count) {
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddLines(path, NULL, points, count);
    CGPathCloseSubpath(path);
    return path;
}

所以,我需要传递确切的数据类型,因为我无法逐个元素地解析它,或者我需要一种方法来每次用户执行特定操作时,我将它的 CGPoint 添加到 CGPoint 数组中:( ( 提前致谢 编辑 : 我已经尝试过 malloc 和制作 c 数组,但函数的结果并不理想,我测试并制作了无限循环到那个 malloc 数组,它太大了,不仅仅是我坐的大小,而且包含垃圾所以结果出错了

这是可变数组

pointToPoints = [NSMutableArray new];
[pointToPoints addObject:[NSValue valueWithCGPoint:tempPoint] ];
CGPoint *points = malloc(sizeof(CGPoint) * mutableArrayOfPoints.count);
for (int i = 0; i < mutableArrayOfPoints.count; i++) {
    points[i] = [mutableArrayOfPoints[i] pointValue];
}

以上是凭记忆。我已经很久没有使用 malloc() 了,所以您可能需要调整语法。

这里会使用您提供的代码从 NSValue 中的 NSArray 创建一个闭合路径,该路径是 CGPoint 创建的:

BOOL isCGPoint(NSValue *value){
    return value && strcmp([value objCType], @encode(CGPoint)) == 0;
}

- (CGPathRef) closedPathFromPointArray:(NSArray *)points{
    CGMutablePathRef path = CGPathCreateMutable();

    if(points.count){
        CGPoint origin = ((NSValue *)points[0]).CGPointValue;
        CGPathMoveToPoint (path, NULL, origin.x, origin.y);

        // see https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/CGPath/#//apple_ref/c/func/CGPathAddLines
        for(NSValue *value in points){
            CGPathAddLineToPoint (path, NULL, value.CGPointValue.x, value.CGPointValue.y);
        }
    }

    CGPathCloseSubpath(path);
    return path;
}

如您所见,您实际上并不需要 malloc,甚至不需要创建 CGPoint 的 C 数组。这假设您只需要此数组来创建封闭路径。 两件额外的注意事项:

  • 请参阅 CGPathAddLines 的注释 link,因为它描述了 CGPathAddLines 的内部工作方式。这为您提供了有关如何进行此操作的提示。
  • 包含 isCGPoint 函数,因此您可以测试给定的 NSValue 实例是否实际上是使用 [NSValue valueWithCGPoint:] 创建的。我之前的回答对此进行了检查,但我认为到处检查都太过分了。无论如何,出于教学目的将其包含在此处。