在UIImageView上使用Tint颜色

我有我自己的UIButton的子类。 我添加UIImageView并添加图像。 我想用色调来描绘图像,但不起作用。

到目前为止我有:

 - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor = [UIColor clearColor]; self.clipsToBounds = YES; self.circleView = [[UIView alloc]init]; self.circleView.backgroundColor = [UIColor whiteColor]; self.circleView.layer.borderColor = [[Color getGraySeparatorColor]CGColor]; self.circleView.layer.borderWidth = 1; self.circleView.userInteractionEnabled = NO; self.circleView.translatesAutoresizingMaskIntoConstraints = NO; [self addSubview:self.circleView]; self.iconView = [[UIImageView alloc]init]; [self.iconView setContentMode:UIViewContentModeScaleAspectFit]; UIImage * image = [UIImage imageNamed:@"more"]; [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; self.iconView.image = image; self.iconView.translatesAutoresizingMaskIntoConstraints = NO; [self.circleView addSubview:self.iconView]; ... 

并在select:

 - (void) setSelected:(BOOL)selected { if (selected) { [self.iconView setTintColor:[UIColor redColor]]; [self.circleView setTintColor:[UIColor redColor]]; } else{ [self.iconView setTintColor:[UIColor blueColor]]; [self.circleView setTintColor:[UIColor blueColor]]; } } 

我做错了什么? (图像的颜色始终保持原样)

而不是这个代码:

 [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; 

你应该有:

 image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; 

你也可以在你的资产上设置这个。 确保您的图像包含所有白色像素+透明。 在这里输入图像说明

在快速2.0+,你可以做:

 let image = UIImage(named: "your_image_name")!.imageWithRenderingMode(.AlwaysTemplate) yourImageView.image = image yourImageView.tintColor = UIColor.blueColor() 

(不能编辑@卓龙中邮)

3.0版本中 ,你可以这样做:

 let image = UIImage(named: "your_image_name")!.withRenderingMode(.alwaysTemplate) yourImageView.image = image yourImageView.tintColor = UIColor.blue 

目标C

 self.imgView.image = [self.imgView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; [self.imgView setTintColor:[UIColor darkGrayColor]]; 

更进一步。 这是UIImageView的一个embedded子类。 (原始问题不是完全解决scheme。)通过将类名称设置为TintedImageView,在Interface Builder中使用。 devise师内部实时更新色彩的变化。

(Swift 3.1,Xcode 8.3)

 import UIKit @IBDesignable class TintedImageView: UIImageView { override func prepareForInterfaceBuilder() { self.configure() } override func awakeFromNib() { super.awakeFromNib() self.configure() } @IBInspectable override var tintColor: UIColor! { didSet { self.configure() } } private func configure() { self.image = self.image?.withRenderingMode(UIImageRenderingMode.alwaysTemplate) } } 

制作imageView

  let imageView = UIImageView(frame: frame!) imageView.contentMode = .ScaleAspectFit imageView.tintColor = tintColor 

制作图像

  let mainBundle = NSBundle.mainBundle() var image = UIImage(named: filename!, inBundle: mainBundle, compatibleWithTraitCollection: nil) image = image?.imageWithRenderingMode(.AlwaysTemplate) 

将它们连接起来

  imageView?.image = image 

显示它

 view.addSubview(imageView)