How can I change image tintColor

后端 未结 13 847
时光说笑
时光说笑 2020-12-13 00:04

I\'m receiving image from a server, then based on a color chosen by the user, the image color will be changed.

I tried the following :

_sketchImageVi         


        
13条回答
  •  温柔的废话
    2020-12-13 00:53

    In Swift you can use this extension: [Based on @VietHung's objective-c solution]

    Swift 5:

    extension UIImage {
          func imageWithColor(color: UIColor) -> UIImage? {
            var image = withRenderingMode(.alwaysTemplate)
            UIGraphicsBeginImageContextWithOptions(size, false, scale)
            color.set()
            image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
            image = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            return image
        }
    }
    

    Previous Swift version:

    extension UIImage {
        func imageWithColor(color: UIColor) -> UIImage? {
            var image = imageWithRenderingMode(.AlwaysTemplate)
            UIGraphicsBeginImageContextWithOptions(size, false, scale)
            color.set()
            image.drawInRect(CGRect(x: 0, y: 0, width: size.width, height: size.height))
            image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
    }
    

提交回复
热议问题