Search code examples
iosuiimageviewuiimagecore-graphics

iOS Changing half of the image's color


I have a single image that looks like this…

enter image description here

What I have to achieve is that I have to change the color of the lower half of this image.. like this one.. enter image description here

I've tried using CAGradientLayer, Masking but no luck getting the result..

any help would be great.. Thanks in advance..

UPDATE 1

This is what em getting after this code.. One thing i need to add is that image is resized before using..

enter image description here

UPDATE 2

enter image description here


Solution

  • you made me some good challenge with this, but here you go:

    Method that return image with bottom half coloured with some colour

    - (UIImage *)image:(UIImage *)image withBottomHalfOverlayColor:(UIColor *)color
    {
        CGRect rect = CGRectMake(0.f, 0.f, image.size.width, image.size.height);
    
        if (UIGraphicsBeginImageContextWithOptions) {
            CGFloat imageScale = 1.f;
            if ([self respondsToSelector:@selector(scale)])
                imageScale = image.scale;
            UIGraphicsBeginImageContextWithOptions(image.size, NO, imageScale);
        }
        else {
            UIGraphicsBeginImageContext(image.size);
        }
    
        [image drawInRect:rect];
    
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetBlendMode(context, kCGBlendModeSourceIn);
    
        CGContextSetFillColorWithColor(context, color.CGColor);
    
        CGRect rectToFill = CGRectMake(0.f, image.size.height*0.5f, image.size.width, image.size.height*0.5f);
        CGContextFillRect(context, rectToFill);
    
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return newImage;
    }
    

    Example of use :

        UIImage *image = [UIImage imageNamed:@"q.png"];
        image = [self image:image withBottomHalfOverlayColor:[UIColor cyanColor]];
        self.imageView.image = image;
    

    My results :enter image description hereenter image description here