动漫人物
这是一个应该做的技巧@interface UIImage(Overlay)@end@implementation UIImage(Overlay)- (UIImage *)imageWithColor:(UIColor *)color1{ UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextTranslateCTM(context, 0, self.size.height); CGContextScaleCTM(context, 1.0, -1.0); CGContextSetBlendMode(context, kCGBlendModeNormal); CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height); CGContextClipToMask(context, rect, self.CGImage); [color1 setFill]; CGContextFillRect(context, rect); UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage;}@end所以你会这样做:theImageView.image = [theImageView.image imageWithColor:[UIColor redColor]];
蛊毒传说
我必须在Swift中使用extension。我以为我会分享我是如何做到的:extension UIImage { func imageWithColor(color1: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) color1.setFill() let context = UIGraphicsGetCurrentContext() as CGContextRef CGContextTranslateCTM(context, 0, self.size.height) CGContextScaleCTM(context, 1.0, -1.0); CGContextSetBlendMode(context, CGBlendMode.Normal) let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect CGContextClipToMask(context, rect, self.CGImage) CGContextFillRect(context, rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage UIGraphicsEndImageContext() return newImage }}用法:theImageView.image = theImageView.image.imageWithColor(UIColor.redColor())斯威夫特4extension UIImage { func imageWithColor(color1: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) color1.setFill() let context = UIGraphicsGetCurrentContext() context?.translateBy(x: 0, y: self.size.height) context?.scaleBy(x: 1.0, y: -1.0) context?.setBlendMode(CGBlendMode.normal) let rect = CGRect(origin: .zero, size: CGSize(width: self.size.width, height: self.size.height)) context?.clip(to: rect, mask: self.cgImage!) context?.fill(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! }}用法:theImageView.image = theImageView.image?.imageWithColor(color1: UIColor.red)