2017-12-02 135 views
0

我目前使用下面的函數來改變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; 
} 

回答

0

讓你的函數的異步版本如下...

- (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