0

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.

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

When I do this: let defaultImage = UIImage(systemName: "person.circle.fill") defaultImage?.withTintColor(.gray, renderingMode: .alwaysOriginal) friendView.image = defaultImage. The image still shows up in the default blue.
@chibro2 withTintColor not change defaultImage, you need use withTintColor return value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.