简体   繁体   English

通过配对来自两个不同NSArray的值来创建CGPoints数组

[英]Create an array of CGPoints by pairing values from two different NSArrays

How to create an array of CGPoints by pairing values from two different NSArrays in objective-c? 如何通过配对objective-c中两个不同NSArray的值来创建一个CGPoints数组?

Lets say I have an Array "A" with the values: 0, 1, 2, 3, 4 假设我有一个数组“A”,其值为: 0, 1, 2, 3, 4
And I also have an Array "B" with the values: 21, 30, 33, 35, 31 我还有一个数组“B”,其值为: 21, 30, 33, 35, 31

I would like to create Array "AB" with CGPoint values: (0,21), (1,30), (2,33), (3,35), (4,31) 我想用CGPoint值创建数组“AB”:( (0,21), (1,30), (2,33), (3,35), (4,31)

Thanks for your help. 谢谢你的帮助。

Note that Objective-C collection classes can only hold objects, so I have assumed your input numbers are held in NSNumber objects. 请注意,Objective-C集合类只能保存对象,因此我假设您的输入数字保存在NSNumber对象中。 This also means that the CGPoint struct s must be held in a NSValue object in the combined array: 这也意味着CGPoint struct必须保存在组合数组中的NSValue对象中:

NSArray *array1 = ...;
NSArray *array2 = ...;
NSMutableArray *pointArray = [[NSMutableArray alloc] init];

if ([array1 count] == [array2 count])
{
    NSUInteger count = [array1 count], i;
    for (i = 0; i < count; i++)
    {
        NSNumber *num1 = [array1 objectAtIndex:i];
        NSNumber *num2 = [array2 objectAtIndex:i];
        CGPoint point = CGPointMake([num1 floatValue], [num2 floatValue]);
        [pointArray addObject:[NSValue valueWithCGPoint:point]];
    } 
}
else
{
    NSLog(@"Array count mis-matched");
}

Someone else posted on making an NSArray of CGPoints, but you asked for an array of CGPoints. 其他人发布了制作CGPoints的NSArray ,但是你要求提供一系列 CGPoints。 This ought to do that: 这应该是这样的:

NSArray* a = @[ @(0.), @(1.), @(2.), @(3.), @(4.) ];
NSArray* b = @[ @(21.), @(30.), @(33.), @(35.), @(31.) ];

const NSUInteger aCount = a.count, bCount = b.count, count = MAX(aCount, bCount);
CGPoint* points = (CGPoint*)calloc(count, sizeof(CGPoint));
for (NSUInteger i = 0; i < count; ++i)
{
    points[i] = CGPointMake(i < aCount ? [a[i] doubleValue] : 0 , i < bCount ? [b[i] doubleValue] : 0.0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM