Objective-C改变图像颜色性能

Objective-C改变图像颜色性能

问题描述:

我目前使用下面的函数来改变PNG图像的颜色,通过颜色滑块设置颜色,所以当滑动颜色时,一切正常,并得到相应的结果图像相应地,我是滑动时滑块的性能只会有问题,它会滞后以及图像颜色更新,需要帮助才能使过程平滑。Objective-C改变图像颜色性能

- (UIImage*)imageWithImage:(UIImage *)sourceImage fixedHue:(CGFloat)hue saturation:(CGFloat)saturation brightness:(CGFloat)brightness alpha:(CGFloat)alpha{ 
    CGSize imageSize = [sourceImage size]; 
    UIGraphicsBeginImageContext(imageSize); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGContextTranslateCTM(context, 0, sourceImage.size.height); 
    CGContextScaleCTM(context, 1.0, -1.0); 

    CGRect rect = CGRectMake(0, 0, sourceImage.size.width, sourceImage.size.height); 

    CGContextSetBlendMode(context, kCGBlendModeNormal); 
    CGContextDrawImage(context, rect, sourceImage.CGImage); 
    CGContextSetBlendMode(context, kCGBlendModeColor); 
    [[UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:alpha] setFill]; 
    CGContextFillRect(context, rect); 
    CGContextSetBlendMode(context, kCGBlendModeDestinationIn); 
    CGContextDrawImage(context, rect, sourceImage.CGImage); 
    CGContextFlush(context); 
    UIImage *editedImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return editedImage; 
} 

让你的函数的异步版本如下...

- (void)imageWithImage:(UIImage *)sourceImage 
       fixedHue:(CGFloat)hue 
      saturation:(CGFloat)saturation 
      brightness:(CGFloat)brightness 
       alpha:(CGFloat)alpha 
      completion:(void (^)(UIImage *))completion { 

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
    dispatch_async(queue, ^{ 
     // call your original function. Use this to create the context... 
     UIGraphicsBeginImageContextWithOptions(imageSize, YES, 0.0); 
     // don't call CGContextFillRect, call... 
     UIRectFill(rect); 
     // don't call CGContextDrawImage, call... 
     [sourceImage drawInRect:rect] 
     // don't call CGContextFlush, don't need to replace that 

     UIImage *image = [self imageWithImage:sourceImage fixedHue:hue saturation:saturation brightness:brightness alpha:alpha]; 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      completion(image); 
     }); 
    }); 
} 

使用方法如下:

- (IBAction)sliderValueChanged:(UISlider *)sender { 
    [self imageWithImage:sourceImage 
       fixedHue:hue 
       saturation:saturation 
       brightness:brightness 
        alpha:alpha 
       completion:^(UIImage *image) { 
        // update the UI here with image 
       }]; 
} 
+0

谢谢DANH,在这条线 CGContextFillRect应用程序崩溃(上下文,rect); 说应该在UI线程上实现,确实在主线程上添加了这条线来调度仍然没有运气 – Development

+0

啊 - 对不起。不要获取当前的上下文。创建一个。将在几分钟后发布修改。 – danh

+0

对不起 - 我只是刚刚仔细阅读你的原代码。你创建了一个CGContext,并且我认为我已经找到了所有需要运行的主要变化(关闭主要的UI操作都是禁止的)。 – danh