開發(fā)中,圖標(biāo)的顏色有時(shí)需要更改讼庇,但是如果讓UI做不同的顏色的圖片放到工程中有沒有必要,此時(shí)伤提,可以采用以下是那種方法巫俺,更改圖標(biāo)的渲染顏色:
UIButton认烁,UIImageView都可以更改顏色
1.更改圖片設(shè)置:
在Assets.xcassets中選中需要更改顏色的圖片:
將Render As更改為Template Image肿男;
此時(shí)如果不給圖片設(shè)置顏色,圖片顏色默認(rèn)為藍(lán)色却嗡;
button.tintColor = [UIColor redColor];
imageView.tintColor = [UIColor redColor];
2.不更改圖片設(shè)置舶沛,直接用代碼更改顏色
對(duì)圖片進(jìn)行操作:
UIImage *theImage = [UIImage imageNamed:@"圖標(biāo)"];
theImage = [theImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
button,imageView設(shè)置圖片:
[button setImage:theImage forState:(UIControlStateNormal)];
button.tintColor = [UIColor redColor];
imageView.image = theImage;
imageView.tintColor = [UIColor redColor];
3.給image添加方法
<1>創(chuàng)建文件
<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:@"圖標(biāo)"];
theImage = [theImage imageWithColor:[UIColor redColor]];
[but setImage:theImage forState:(UIControlStateNormal)];
imageView.image = theImage;