ios拓展18-图片纯色渲染分类

开发中,如果对于同一套图,需要设置不同颜色,可以通过程序自行渲染

1.方法声明
#import 

@interface UIImage (Tint)

/**
 *  为图片填充自定义颜色
 *
 *  @param tintColor 需要填充的颜色
 *
 *  @return 填充后的颜色
 */
- (UIImage *)imageWithTintColor:(UIColor *)tintColor;

/**
 *  为图片填充自定义颜色
 *
 *  @param tintColor 需要填充的颜色
 *
 *  @return 填充后的颜色
 */
- (UIImage *)imageWithGradientTintColor:(UIColor *)tintColor;

@end
2.方法实现
#import "UIImage+Tint.h"

@implementation UIImage (Tint)

- (UIImage *) imageWithTintColor:(UIColor *)tintColor
{
    return [self imageWithTintColor:tintColor blendMode:kCGBlendModeDestinationIn];
}

- (UIImage *) imageWithGradientTintColor:(UIColor *)tintColor
{
    return [self imageWithTintColor:tintColor blendMode:kCGBlendModeOverlay];
}

- (UIImage *) imageWithTintColor:(UIColor *)tintColor blendMode:(CGBlendMode)blendMode
{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
    [tintColor setFill];
    CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
    UIRectFill(bounds);
    
    [self drawInRect:bounds blendMode:blendMode alpha:1.0f];
    
    if (blendMode != kCGBlendModeDestinationIn) {
        [self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
    }
    
    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return tintedImage;
}

@end

你可能感兴趣的:(ios拓展18-图片纯色渲染分类)