ios UIImageRenderingModeAlwaysTemplate不会忽略不透明度

时间:2017-09-25 11:10:56

标签: ios uiimageview uiimage

我正在尝试动态更改设计师提供给我的图像的颜色和不透明度。当然,它可以与以下代码无缝协作:

_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?

1 个答案:

答案 0 :(得分: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
    }
}