objective-c - 为渐变位置创建 CGFloat 数组

标签 objective-c macos cocoa nsgradient

我正在尝试从字典数组(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/

相关文章:

iphone - 旋转 iPhone/iPad 时正确分配间距?

macos - 无密码 SSH 登录

c++ wait_until奇怪的超时行为

cocoa - NSTextView 的内在内容大小

objective-c - 如何将 "normal"NSDocument 逻辑添加到修改后的基于项目的架构中?

iOS10 UIImageWriteToSavedPhotosAlbum TCC__CRASHING_DUE_TO_PRIVACY_VIOLATION

iphone - 在 iOS 中创建 JsonString

iphone - 动画完成后想调用一些方法

python - 如何在 Mac OS X 10.8 上安装 hg 转换所需的 python 颠覆绑定(bind)?

macos - "Check For Updates"使用 Sparkle 框架禁用(灰显)