2017-09-25 83 views
0

我想动态地改变设计师给我的图像的颜色和不透明度。当然,用下面的代码无缝工作:ios UIImageRenderingModeAlwaysTemplate不忽略不透明

_imgViewForMenu.tintColor = [_lblForMenu.textColor colorWithAlphaComponent:1.0f]; 
// This alpha component wont affect the png image with 38% opacity. 
// You will never get full black image with [UIColor blackColor] 
// and alpha component 1.0 

_imgViewForMenu.image = [imageForMenuIcon imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; 

这是可行的,但只有当图像有没有自己的不透明度。除此之外,在代码的评论中,它不会工作。

所以问题是,你如何呈现图像忽略其颜色组件以及不透明度。像UITabBar和UIBarButonItem这样的系统控制似乎很容易。为什么不用UIImageView呢?

回答

0

试试这个:

extension UIImage { 
    func tinted(with color: UIColor) -> UIImage? { 
     let image = withRenderingMode(.alwaysTemplate) 
     UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale) 
     color.set() 
     image.draw(in: CGRect(x: 0.0, y: 0.0, width: image.size.width, height: image.size.height)) 
     let tintedImage = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     return tintedImage 
    } 
}