Changing UIImage color

前端 未结 13 1459
我寻月下人不归
我寻月下人不归 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:54

    Swift 3.0 version of Anna's marvelous code:

    extension UIImage{
    
        static func multiplyImageByConstantColor(image:UIImage,color:UIColor)-> UIImage {
            let backgroundSize = image.size
            UIGraphicsBeginImageContext(backgroundSize)
    
            let ctx = UIGraphicsGetCurrentContext()!
    
            var backgroundRect=CGRect()
            backgroundRect.size = backgroundSize
            backgroundRect.origin.x = 0
            backgroundRect.origin.y = 0
    
            let myFloatForR = 0
            var r = CGFloat(myFloatForR)
            let myFloatForG = 0
            var g = CGFloat(myFloatForG)
            let myFloatForB = 0
            var b = CGFloat(myFloatForB)
            let myFloatForA = 0
            var a = CGFloat(myFloatForA)
    
            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(.multiply)
            ctx.draw(image.cgImage!, in: imageRect)
    
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return newImage!
        }
    }
    

提交回复
热议问题