Changing UIImage color

前端 未结 13 1503
我寻月下人不归
我寻月下人不归 2020-11-28 19:28

I\'m trying to change color of UIImage. My code:

-(UIImage *)coloredImage:(UIImage *)firstImage withColor:(UIColor *)color {
    UIGraphicsBeginImageContext(         


        
13条回答
  •  余生分开走
    2020-11-28 19:48

    Here's my adaptation of @Anna's answer. Two key points here:

    • Use destinationIn blending mode
    • Call UIGraphicsBeginImageContextWithOptions(backgroundSize, false, UIScreen.main.scale) to get smooth image

    Code in in Swift 3:

    extension UIImage {
    
        static func coloredImage(image: UIImage?, color: UIColor) -> UIImage? {
    
            guard let image = image else {
                return nil
            }
    
            let backgroundSize = image.size
            UIGraphicsBeginImageContextWithOptions(backgroundSize, false, UIScreen.main.scale)
    
            let ctx = UIGraphicsGetCurrentContext()!
    
            var backgroundRect=CGRect()
            backgroundRect.size = backgroundSize
            backgroundRect.origin.x = 0
            backgroundRect.origin.y = 0
    
            var r:CGFloat = 0
            var g:CGFloat = 0
            var b:CGFloat = 0
            var a:CGFloat = 0
            color.getRed(&r, green: &g, blue: &b, alpha: &a)
            ctx.setFillColor(red: r, green: g, blue: b, alpha: a)
            ctx.fill(backgroundRect)
    
            var imageRect = CGRect()
            imageRect.size = image.size
            imageRect.origin.x = (backgroundSize.width - image.size.width) / 2
            imageRect.origin.y = (backgroundSize.height - image.size.height) / 2
    
            // Unflip the image
            ctx.translateBy(x: 0, y: backgroundSize.height)
            ctx.scaleBy(x: 1.0, y: -1.0)
    
            ctx.setBlendMode(.destinationIn)
            ctx.draw(image.cgImage!, in: imageRect)
    
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return newImage!
        }
    }
    

提交回复
热议问题