How to programmatically change the hue of UIImage?

后端 未结 5 868
南笙
南笙 2020-12-01 01:26

I am very new to the image processing. I have to implement hue effect in my iPhone application project. Therefore, I need to change the hue of UIImage. Please p

5条回答
  •  盖世英雄少女心
    2020-12-01 01:48

    Taking Dondragmer's excellent fixed hue example as a starting point. Here is my modification, to fix the problem of transparent areas being set with the same hue.

    - (UIImage*) imageWithImage:(NSString *)name fixedHue:(CGFloat) hue alpha:(CGFloat) alpha;
    // Note: the hue input ranges from 0.0 to 1.0, both red.  Values outside this range will be clamped to 0.0 or 1.0.
    {
        UIImage *source = [UIImage imageNamed:name];
    
        // Find the image dimensions.
        CGSize imageSize = [source size];
        CGRect imageExtent = CGRectMake(0,0,imageSize.width,imageSize.height);
    
        // Create a context containing the image.
        UIGraphicsBeginImageContext(imageSize);
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        [source drawAtPoint:CGPointMake(0,0)];
    
        // Setup a clip region using the image
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, 0, source.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextClipToMask(context, imageExtent, source.CGImage);
    
        //[[UIColor colorWithHue:hue saturation:1.0 brightness:1 alpha:alpha] set];
        CGContextFillRect(context, imageExtent);
    
        // Draw the hue on top of the image.
        CGContextDrawImage(context, imageExtent, source.CGImage);
        CGContextSetBlendMode(context, kCGBlendModeHue);
        [[UIColor colorWithHue:hue saturation:1.0 brightness:1 alpha:alpha] set];
        UIBezierPath *imagePath = [UIBezierPath bezierPathWithRect:imageExtent];
        [imagePath fill];
    
        CGContextRestoreGState(context); // remove clip region
    
        // Retrieve the new image.
        UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return result;
    }
    

    Thanks to:

    How to change hue of UIIMAGE having transparent area?

    CGContextClipToMask UIImage Mask Invert Up and Down

提交回复
热议问题