开发中,图标的颜色有时需要更改,但是如果让UI做不同的颜色的图片放到工程中有没有必要,此时,可以采用以下是那种方法,更改图标的渲染颜色:
UIButton,UIImageView都可以更改颜色
1.更改图片设置:
在Assets.xcassets中选中需要更改颜色的图片:
将Render As更改为Template Image;
此时如果不给图片设置颜色,图片颜色默认为蓝色;
button.tintColor = [UIColor redColor];
imageView.tintColor = [UIColor redColor];
2.不更改图片设置,直接用代码更改颜色
对图片进行操作:
UIImage *theImage = [UIImage imageNamed:@"图标"];
theImage = [theImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
button,imageView设置图片:
[button setImage:theImage forState:(UIControlStateNormal)];
button.tintColor = [UIColor redColor];
imageView.image = theImage;
imageView.tintColor = [UIColor redColor];
3.给image添加方法
<1>创建文件
<2>UIImage+Color.h暴露方法
- (UIImage *)imageWithColor:(UIColor *)color;
<3>UIImage+Color.m中写方法
- (UIImage *)imageWithColor:(UIColor *)color
{
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);
[color setFill];
CGContextFillRect(context, rect);
UIImage*newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
<4>方法使用:
UIImage *theImage = [UIImage imageNamed:@"图标"];
theImage = [theImage imageWithColor:[UIColor redColor]];
[but setImage:theImage forState:(UIControlStateNormal)];
imageView.image = theImage;