How can I color a UIImage in Swift?

后端 未结 20 2271
执念已碎
执念已碎 2020-11-29 18:27

I have an image called arrowWhite. I want to colour this image to black.

func attachDropDownArrow() -> NSMutableAttributedString {
    let im         


        
20条回答
  •  甜味超标
    2020-11-29 18:53

    I found the solution by H R to be most helpful but adapted it slightly for Swift 3

    extension UIImage {
    
        func maskWithColor( color:UIColor) -> UIImage {
    
             UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
             let context = UIGraphicsGetCurrentContext()!
    
             color.setFill()
    
             context.translateBy(x: 0, y: self.size.height)
             context.scaleBy(x: 1.0, y: -1.0)
    
             let rect = CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height)
             context.draw(self.cgImage!, in: rect)
    
             context.setBlendMode(CGBlendMode.sourceIn)
             context.addRect(rect)
             context.drawPath(using: CGPathDrawingMode.fill)
    
             let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
             UIGraphicsEndImageContext()
    
             return coloredImage!
        }
    }
    

    This takes into consideration scale and also does not produce a lower res image like some other solutions. Usage :

    image = image.maskWithColor(color: .green )
    

提交回复
热议问题