美文网首页
UIImage的Category,通过UIColor创建UIIm

UIImage的Category,通过UIColor创建UIIm

作者: 彩虹兔兔 | 来源:发表于2017-08-29 17:06 被阅读0次

项目中经常遇到button在enable和disabled状态下背景色不同。UIButton只提供setBackgroundImage:(nullable UIImage *)image forState:(UIControlState)state的方法来设置背景色。

如果只给color直接设置不了。

所以需要通过UIColor来初始化UIImage的方法
extension UIImage {

convenience init?(color: UIColor) {

let rect = CGRect(0, 0, 1, 1)

UIGraphicsBeginImageContext(rect.size)

color.setFill()

UIRectFill(rect)

let image = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()

guard let cgImage = image?.cgImage else { return nil }

self.init(cgImage: cgImage)

}

}

相关文章

网友评论

      本文标题:UIImage的Category,通过UIColor创建UIIm

      本文链接:https://www.haomeiwen.com/subject/lpxadxtx.html