设置 UIImage 颜色

Set UIImage color

我在 swift 4,我的目标是在代码中更改系统的颜色 UIImage。我用

声明图像
    let defaultImage = UIImage(systemName: "person.circle.fill")

但是当我改变它的色调时:

 let grayDefaultImage = defaultImage?.withTintColor(.gray)

grayDefaultImage仍然显示标准的蓝色。接下来我使用扩展

//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!
    }
}

并且图像以非常 "pixelated" 或 "low res" 的形式呈现。

withTintColor(_:) 说:The new image uses the same rendering mode as the original image.

所以如果原始图像的渲染模式是.alwaysTemplate,意味着图像将忽略它的颜色信息。您需要将模式设置为 .alwaysOriginal:

defaultImage?.withTintColor(.gray, renderingMode: .alwaysOriginal)