有时候,我们需要改变图片的颜色,如图片中有白色字体,我们要把它改成黑色,这时候我们要对UIImageView渲染颜色。代码如下
参数image是原图,color是要渲染的颜色
CGContext的纵坐标和UIKit的纵坐标相反,所以要做坐标变换,原图的左下角是原点,每点的纵坐标取反
+ (UIImage *)imageWithImage:(UIImage *)image tintColor:(UIColor *)color {
UIGraphicsBeginImageContextWithOptions(image.size,NO, image.scale);
CGContextRef context =UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0, image.size.height);
CGContextScaleCTM(context, 1, -1);
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
CGContextClipToMask(context, rect, image.CGImage);
UIRectFillUsingBlendMode(rect,kCGBlendModeNormal);
UIImage *newImage =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}