How can I color a UIImage in Swift?

后端 未结 20 2268
执念已碎
执念已碎 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:50

    I ended up with this because other answers either lose resolution or work with UIImageView, not UIImage, or contain unnecessary actions:

    Swift 3

    extension UIImage {
    
        public func maskWithColor(color: UIColor) -> UIImage {
    
            UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
            let context = UIGraphicsGetCurrentContext()!
    
            let rect = CGRect(origin: CGPoint.zero, size: size)
    
            color.setFill()
            self.draw(in: rect)
    
            context.setBlendMode(.sourceIn)
            context.fill(rect)
    
            let resultImage = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            return resultImage
        }
    
    }
    

提交回复
热议问题