我正在尝试从字典数组(colorArray2)中创建渐变颜色。该字典包含 5 个键:r、g、b、a、p。 r、g、b、a 是组件值(字符串),p 是位置。我正在尝试使用 initWithColors:atLocations:colorSpace 创建渐变颜色。目前,我有以下内容。
NSGradient *aGradient;
NSColorSpace *space = [NSColorSpace genericRGBColorSpace];
NSMutableArray *cArray = [[NSMutableArray alloc] initWithObjects:nil]; // storing colors
NSMutableArray *pArray = [[NSMutableArray alloc] initWithObjects:nil]; // storing locations
for (NSInteger i2 = 0; i2 < colorArray2.count; i2++) {
NSString *r = [[colorArray2 objectAtIndex:i2] objectForKey:key2a];
NSString *g = [[colorArray2 objectAtIndex:i2] objectForKey:key2b];
NSString *b = [[colorArray2 objectAtIndex:i2] objectForKey:key2c];
NSString *a = [[colorArray2 objectAtIndex:i2] objectForKey:key2d];
NSString *p = [[colorArray2 objectAtIndex:i2] objectForKey:key2e];
NSColor *color = [NSColor colorWithSRGBRed:[r integerValue]/255.0f green:[g integerValue]/255.0f blue:[b integerValue]/255.0f alpha:[a integerValue]/100.0f];
[cArray addObject:color];
[pArray addObject:[NSNumber numberWithDouble:[p doubleValue]]];
}
所以我有一个包含颜色的数组(cArray)。我不知道如何创建位置数组。根据文档,locations 是一个 CGFloat 值数组,其中包含渐变中每种颜色的位置。如何枚举任何内容来创建 float 组?
感谢您的帮助。
更新
更具体地说,我如何使 pArray 得到类似的东西
double d[] = {0.1, 0.2, 0.3, 0.5, 1.0};
这样我就可以拥有
aGradient = [[NSGradient alloc] initWithColors:cArray atLocations:d colorSpace:space];
最佳答案
NSGradient's documentation声明 locations
参数应为 const CGFloat*
类型,因此您不能使用 NSArray*
。以下内容应该有效:
// Allocate a C-array with the same length of colorArray2
CGFloat* pArray = (CGFloat*)malloc(colorArray2.count * sizeof(CGFloat));
for (NSInteger i2 = 0; i2 < colorArray2.count; i2++) {
// Extract location
NSString* p = [[colorArray2 objectAtIndex:i2] objectForKey:key2e];
pArray[i2] = [p doubleValue];
}
// Do whaterver with pArray
...
// Remember to free it
free(pArray);
关于objective-c - 为渐变位置创建 CGFloat 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19603198/