我想使用 Core Image 对照片应用线性渐变。这是我正在使用的代码(或者您可以在 Xcode 项目中查看它:http: //cl.ly/2Z0Z2f1a3Q27):
CIContext *coreImageContext = [CIContext contextWithOptions:nil];
CIFilter *gradientFilter = [CIFilter filterWithName:@"CILinearGradient"];
[gradientFilter setDefaults];
CIColor *startColor = [CIColor colorWithCGColor:[UIColor yellowColor].CGColor];
CIColor *endColor = [CIColor colorWithCGColor:[UIColor blackColor].CGColor];
CIVector *startVector = [CIVector vectorWithX:100 Y:0];
CIVector *endVector = [CIVector vectorWithX:100 Y:100];
[gradientFilter setValue:startVector forKey:@"inputPoint0"];
[gradientFilter setValue:endVector forKey:@"inputPoint1"];
[gradientFilter setValue:startColor forKey:@"inputColor0"];
[gradientFilter setValue:endColor forKey:@"inputColor1"];
UIImage *originalImage = [UIImage imageNamed:@"testImage.jpeg"];
CIImage *ciImage = [CIImage imageWithCGImage:originalImage.CGImage];
[gradientFilter setValue:ciImage forKey:kCIInputImageKey];
CIImage *resultCIImage = [gradientFilter valueForKey:kCIOutputImageKey];
CGImageRef resultCGImage = [coreImageContext createCGImage:resultCIImage fromRect:[resultCIImage extent]];
UIImage *resultUIImage = [UIImage imageWithCGImage:resultCGImage scale:[[UIScreen mainScreen] scale] orientation:UIImageOrientationUp];
CGImageRelease(resultCGImage);
UIImageView *filteredImageView = [[UIImageView alloc] initWithImage:resultUIImage];
在设备(iPhone 5、iOS 6.0.1)和模拟器(iOS 6)上运行此代码会产生异常:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<CILinearGradient 0x1f857ee0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key inputImage.'
发生异常的行是[gradientFilter setValue:ciImage forKey:kCIInputImageKey]
。
这是一个示例 Xcode 项目,您可以构建它以查看此错误:http ://cl.ly/2Z0Z2f1a3Q27