簡體   English   中英

通過配對來自兩個不同NSArray的值來創建CGPoints數組

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

如何通過配對objective-c中兩個不同NSArray的值來創建一個CGPoints數組?

假設我有一個數組“A”,其值為: 0, 1, 2, 3, 4
我還有一個數組“B”,其值為: 21, 30, 33, 35, 31

我想用CGPoint值創建數組“AB”:( (0,21), (1,30), (2,33), (3,35), (4,31)

謝謝你的幫助。

請注意,Objective-C集合類只能保存對象,因此我假設您的輸入數字保存在NSNumber對象中。 這也意味着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");
}

其他人發布了制作CGPoints的NSArray ,但是你要求提供一系列 CGPoints。 這應該是這樣的:

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