可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 }