How can I tint a UIImage with gradient?

后端 未结 4 2053
攒了一身酷
攒了一身酷 2020-12-12 18:37

I searched everywhere but didn\'t find the solution. I have image 1. How can I programatically tint them with gradient to get images 2 and 3? Here are those images:

4条回答
  •  孤街浪徒
    2020-12-12 18:42

    EDIT: Here is a version which supports non-retina and retina displays

    The method can be used as a category for UIImage

    + (UIImage *)imageWithGradient:(UIImage *)img startColor:(UIColor *)color1 endColor:(UIColor *)color2 {
        UIGraphicsBeginImageContextWithOptions(img.size, NO, img.scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextTranslateCTM(context, 0, img.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
    
        CGContextSetBlendMode(context, kCGBlendModeNormal);
        CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
        //CGContextDrawImage(context, rect, img.CGImage);
    
        // Create gradient
        NSArray *colors = [NSArray arrayWithObjects:(id)color2.CGColor, (id)color1.CGColor, nil];
        CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
        CGGradientRef gradient = CGGradientCreateWithColors(space, (__bridge CFArrayRef)colors, NULL);
    
        // Apply gradient
        CGContextClipToMask(context, rect, img.CGImage);
        CGContextDrawLinearGradient(context, gradient, CGPointMake(0,0), CGPointMake(0, img.size.height), 0);
        UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        CGGradientRelease(gradient);
        CGColorSpaceRelease(space);
    
        return gradientImage;
    }
    

    Edit: added change by sobri

提交回复
热议问题