2017-09-25 19 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 
    } 
} 
関連する問題