Reputation: 4895
I am on swift 4, and my goal is to change the color of a system UIImage
in code. I declare the image with
let defaultImage = UIImage(systemName: "person.circle.fill")
But when I change its tint color with:
let grayDefaultImage = defaultImage?.withTintColor(.gray)
The grayDefaultImage
still display the standard blue color. Next I use an extension
//MARK: -UIImage extension
extension UIImage {
/// @Todo: this blurs the image for some reason
func imageWithColor(color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
color.setFill()
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: 0, y: self.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
context?.setBlendMode(CGBlendMode.normal)
let rect = CGRect(origin: .zero, size: CGSize(width: self.size.width, height: self.size.height))
context?.clip(to: rect, mask: self.cgImage!)
context?.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
And the image renders in a very "pixelated" or "low res" form.
Upvotes: 0
Views: 234
Reputation: 146
withTintColor(_:) say: The new image uses the same rendering mode as the original image.
So if original image's rendering mode is .alwaysTemplate
, means image will ignoring its color information. you need set mode to .alwaysOriginal
:
defaultImage?.withTintColor(.gray, renderingMode: .alwaysOriginal)
Upvotes: 1