第一种方法
+ (UIImage *)changeImage:(UIImage *)img withColor:(UIColor *)color {
// 获取画布
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);
CGContextClipToMask(context, rect, img.CGImage);
[color setFill];
CGContextFillRect(context, rect);
//创建获取图片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
第二种方法,创建一个UIImage的Category
.h文件
@interface UIImage (ChangeColor)
- (UIImage*)imageChangeColor:(UIColor*)color;
@end
.m文件
@implementation UIImage (ChangeColor)
- (UIImage *)imageChangeColor:(UIColor *)color {
//获取画布
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
//画笔沾取颜色
[color setFill];
CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
UIRectFill(bounds);
//绘制一次
[self drawInRect:bounds blendMode:kCGBlendModeOverlay alpha:1.0f];
//再绘制一次
[self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
//获取图片
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
@end