I have a UIImage
that I want to fill with UIColor
I've tried this code but the app crashes on the 10th row.
Here's the code:
extension UIImage {
func imageWithColor(_ color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: 0.0, y: size.height)
context?.scaleBy(x: 1.0, y: -1.0)
context?.setBlendMode(CGBlendMode.normal)
let rect = CGRect(origin: CGPoint.zero, size: size)
context?.clip(to: rect, mask: context as! CGImage)// crashes
color.setFill()
context?.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
return newImage!
}
}
The problem is probably on context?.clip(to: rect, mask: context as! CGImage)
(I think I shouldn't send context
as the mask, but what should I send? Both CGImage()
and CGImage.self
don't work.
When you set this image later to UIButton or UIImageView - just change tint color of that control, and image will be drawn using tint color you specified.
You have to do as follow:
Simplest way to doing this
You need to end the image context when you finish drawing:
Or you could add a category method for UIImage:
Using as: