如何在iOS中应用Core Image Linear Gradient过滤器?

时间:2013-01-28 22:44:09

标签: ios cocoa-touch core-image

我想使用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

1 个答案:

答案 0 :(得分:1)

CILinearGradient只有四个属性 - 两点和两种颜色。您必须使用CISourceOverCompositing过滤器链接CILinearGradient以在图像上合成渐变。请参阅过滤器参考:

https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/CoreImageFilterReference/Reference/reference.html#//apple_ref/doc/filter/ci/CILinearGradient