有時(shí)候我們需要同一張圖片在不同情況下顯示不同的顏色绽媒,讓UI出圖費(fèi)時(shí)費(fèi)力伏伯,自己出圖自己又懶(別和我比懶浩考,我懶得和你比)壤圃,所以還是用代碼解決吧??
Swift版
//MARK: 改變圖片顏色
extension UIImage{
/// 更改圖片顏色
public func maskImageWithColor(color : UIColor) -> UIImage{
UIGraphicsBeginImageContext(self.size)
color.setFill()
let bounds = CGRect.init(x: 0, y: 0, width: self.size.width, height: self.size.height)
UIRectFill(bounds)
self.draw(in: bounds, blendMode: CGBlendMode.destinationIn, alpha: 1.0)
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage!
}
}
OC版
- (UIImage *) maskImageWithColor:(UIColor *)color
{
NSParameterAssert(color != nil);
CGRect imageRect = CGRectMake(0.0f, 0.0f, self.size.width, self.size.height);
UIImage *newImage = nil;
UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, self.scale);
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextScaleCTM(context, 1.0f, -1.0f);
CGContextTranslateCTM(context, 0.0f, -(imageRect.size.height));
CGContextClipToMask(context, imageRect, self.CGImage);
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, imageRect);
newImage = UIGraphicsGetImageFromCurrentImageContext();
}
UIGraphicsEndImageContext();
return newImage;
}