開發(fā)中,如果對于同一套圖,需要設(shè)置不同顏色,可以通過程序自行渲染
1.方法聲明
#import <UIKit/UIKit.h>
@interface UIImage (Tint)
/**
* 為圖片填充自定義顏色
*
* @param tintColor 需要填充的顏色
*
* @return 填充后的顏色
*/
- (UIImage *)imageWithTintColor:(UIColor *)tintColor;
/**
* 為圖片填充自定義顏色
*
* @param tintColor 需要填充的顏色
*
* @return 填充后的顏色
*/
- (UIImage *)imageWithGradientTintColor:(UIColor *)tintColor;
@end
2.方法實現(xiàn)
#import "UIImage+Tint.h"
@implementation UIImage (Tint)
- (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
{
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
[tintColor setFill];
CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
UIRectFill(bounds);
[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;
}
@end