有时为了不麻烦设计师,或者为了动画,需要动态的更改图标的颜色,上网搜索了一下,竟然没有找到Swift版本,于是照着Objective-C给UIImage扩展了个分类,方便使用
extension UIImage{
/// 更改图片颜色
public func imageWithTintColor(color : UIColor) -> UIImage{
UIGraphicsBeginImageContext(self.size)
color.setFill()
let bounds = CGRect.init(x: 0, y: 0, width: self.size.width, height: self.size.height)
UIRectFill(bounds)
self.draw(in: bounds, blendMode: CGBlendMode.destinationIn, alpha: 1.0)
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage!
}
}
用法示例
let setBtn = UIButton.init(type: .custom)
setBtn.frame = CGRect.init(x: kScreenW-12-44, y: 20, width: 44, height: 44)
let tintImage = UIImage.init(named: "mine_settingIcon2_19x19_")
let newImage = tintImage?.imageWithTintColor(color: UIColor.white)
setBtn.setImage(newImage, for: .normal)