How to apply a tintColor to a UIImage?

匿名 (未验证) 提交于 2019-12-03 01:12:01

问题:

I have a UIImage that is a small symbol that is all black. The UIImage is getting set in a custom UIButton subclass I have. Is it possible to have the image to apply the tintColor to it, so instead of the black image it changes colors to whatever the tintColor is?

I'm just trying to avoid creating new assets.

// here I want defaultImageName (that is black) to use the tintColor (that is white) [self setImage:[UIImage imageNamed:defaultImageName] forState:UIControlStateNormal]; 

回答1:

If you are just supporting iOS 7 you can use tintColor and UIImageRenderingModeAlwaysTemplate

This article covers that:

https://www.captechconsulting.com/blogs/ios-7-tutorial-series-tint-color-and-easy-app-theming

If you need to support an earlier version you may want to consider this thread

How would I tint an image programmatically on the iPhone?



回答2:

Here's how I use tint colors and opacities in IOS 9 with Swift -

//apply a color to an image //ref - http://stackoverflow.com/questions/28427935/how-can-i-change-image-tintcolor //ref - https://www.captechconsulting.com/blogs/ios-7-tutorial-series-tint-color-and-easy-app-theming func getTintedImage() -> UIImageView {      var image :UIImage     var imageView :UIImageView      image = UIImage(named: "someAsset")!     let size  : CGSize = image.size     let frame : CGRect = CGRectMake((UIScreen.mainScreen().bounds.width-86)/2, 600, size.width, size.height)      let redCover : UIView = UIView(frame: frame)      redCover.backgroundColor = UIColor.redColor()     redCover.layer.opacity = 0.75      imageView = UIImageView();     imageView.image = image.imageWithRenderingMode(UIImageRenderingMode.Automatic)      imageView.addSubview(redCover)      return imageView } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!