不能CIFilter图像两次CGImage没有秒的时间

时间:2014-08-12 19:36:36

标签: ios uiimage cifilter

我在自定义UIImageView类中对过滤后的图像应用过滤器,这样当我设置“hue”时,它会过滤图像。但是,当我调用以下代码时,[[self image] CGImage]第一次返回正确的值。第二次围绕[[自我图像] CGImage]是零,所以CIFilter返回也是零。

有更好的方法吗?

- (void)setHue:(CGFloat)aHue
{
    hue = aHue;
    NSLog( @"CG Image? %@", [[self image] CGImage] );
    CIFilter *filter = [CIFilter filterWithName:@"CIHueAdjust"];
    [filter setDefaults];
    [filter setValue:[CIImage imageWithCGImage:[[self image] CGImage]]
              forKey:@"inputImage"];
    NSLog( @"Setting new hue %f", aHue );
    [filter setValue:[NSNumber numberWithFloat:aHue] forKey:@"inputAngle"];
    [self setImage:[UIImage imageWithCIImage:[filter valueForKey:@"outputImage"]]];

    NSLog( @"Output image %@", [self image] );
}

1 个答案:

答案 0 :(得分:2)

UIImage可以由CGImageCIImage支持。运行此功能一次并调用[UIImage imageWithCIImage]后,新的UIImage现在由CIImage支持。

这实际上很好,因为下次这个功能可以更快地运行!您只需检查是否存在CIImage并直接使用它:

- (void)setHue:(CGFloat)aHue
{
    hue = aHue;
    NSLog( @"CG Image? %@", [[self image] CGImage] );
    CIFilter *filter = [CIFilter filterWithName:@"CIHueAdjust"];
    [filter setDefaults];
    if ([[self image] CGImage]) {
      [filter setValue:[CIImage imageWithCGImage:[[self image] CGImage]] forKey:@"inputImage"];
    }
    else {
      [filter setValue:[[self image] CIImage] forKey:@"inputImage"];
    }

    NSLog( @"Setting new hue %f", aHue );
    [filter setValue:[NSNumber numberWithFloat:aHue] forKey:@"inputAngle"];
    [self setImage:[UIImage imageWithCIImage:[filter valueForKey:@"outputImage"]]];

    NSLog( @"Output image %@", [self image] );
}