关注微信公众号【科技小弟】,了解第一手iOS小知识。
今天介绍一下怎么修改图片的颜色。
.h文件代码:
科技小弟(https://www.jianshu.com/u/23c527245f22)
#import <UIKit/UIKit.h>
@interface UIImage (YYChangePictureColor)
/**
* 修改图片颜色(如何使用:[[UIImage imageNamed:@"image"] imageWithTintColor:[UIColor orangeColor]]; )
*
* @param tintColor 指定颜色
*
* @return 图片
*/
- (UIImage *)imageWithTintColor:(UIColor *)tintColor;
- (UIImage *)imageWithGradientTintColor:(UIColor *)tintColor;
@end
.m文件代码:
#import "UIImage+YYChangePictureColor.h"
@implementation UIImage (YYChangePictureColor)
- (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;
}
@end
怎么使用?我们先找一张图片:
1这是一个白色图标,用于后退按钮,如果我们想把它改成其他颜色呢?
比如我们想把它改成蓝色,调用:
[_backButton setImage:[[UIImage imageNamed:@"common_back"] imageWithTintColor:[UIColor blueColor]] forState:UIControlStateNormal];
结果展示:
2看,它已经变成蓝色了,完美!
网友评论