How can I color a UIImage in Swift?

后端 未结 20 2270
执念已碎
执念已碎 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 19:02

    I have modified the extension found here: Github Gist, for Swift 3 which I have tested in the context of an extension for UIImage.

    func tint(with color: UIColor) -> UIImage 
    {
       UIGraphicsBeginImageContext(self.size)
       guard let context = UIGraphicsGetCurrentContext() else { return self }
    
       // flip the image
       context.scaleBy(x: 1.0, y: -1.0)
       context.translateBy(x: 0.0, y: -self.size.height)
    
       // multiply blend mode
       context.setBlendMode(.multiply)
    
       let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
       context.clip(to: rect, mask: self.cgImage!)
       color.setFill()
       context.fill(rect)
    
       // create UIImage
       guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else { return self }
       UIGraphicsEndImageContext()
    
       return newImage
    }
    

提交回复
热议问题