前一段时间接到一个需求,说我们的应用需要换一整套皮肤,图片的形状大小尺寸甚至命名都不用修改,无疑这个时候UI设计师和我们的工作显得有些重复而笨重。
无意间找到了一个用代码修改图片颜色,代码无痛接入,简直酸爽!
@interface UIImage (TintCorlor)
///修改图片颜色
- (UIImage *) imageWithTintColor:(UIColor *)tintColor;
///修改图片颜色 同时保留透明度
- (UIImage *) imageWithGradientTintColor:(UIColor *)tintColor;
@end
- (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{
//We want to keep alpha, set opaque to NO; Use 0.0f for scale to use the scale factor of the device’s main screen.
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
[tintColor setFill];
CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
UIRectFill(bounds);
//Draw the tinted image in context
[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;
}