How can I color a UIImage in Swift?

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

    Swift 4 and 5

    extension UIImageView {
      func setImageColor(color: UIColor) {
        let templateImage = self.image?.withRenderingMode(.alwaysTemplate)
        self.image = templateImage
        self.tintColor = color
      }
    }
    

    Call like this:

    let imageView = UIImageView(image: UIImage(named: "your_image_name"))
    imageView.setImageColor(color: UIColor.purple)
    

    Alternativ For Swift 3, 4 or 5

    extension UIImage {
    
        func maskWithColor(color: UIColor) -> UIImage? {
            let maskImage = cgImage!
    
            let width = size.width
            let height = size.height
            let bounds = CGRect(x: 0, y: 0, width: width, height: height)
    
            let colorSpace = CGColorSpaceCreateDeviceRGB()
            let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
            let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!
    
            context.clip(to: bounds, mask: maskImage)
            context.setFillColor(color.cgColor)
            context.fill(bounds)
    
            if let cgImage = context.makeImage() {
                let coloredImage = UIImage(cgImage: cgImage)
                return coloredImage
            } else {
                return nil
            }
        }
    
    }
    

    For Swift 2.3

    extension UIImage {
    func maskWithColor(color: UIColor) -> UIImage? {
    
        let maskImage = self.CGImage
        let width = self.size.width
        let height = self.size.height
        let bounds = CGRectMake(0, 0, width, height)
    
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
        let bitmapContext = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, colorSpace, bitmapInfo.rawValue) //needs rawValue of bitmapInfo
    
        CGContextClipToMask(bitmapContext, bounds, maskImage)
        CGContextSetFillColorWithColor(bitmapContext, color.CGColor)
        CGContextFillRect(bitmapContext, bounds)
    
        //is it nil?
        if let cImage = CGBitmapContextCreateImage(bitmapContext) {
            let coloredImage = UIImage(CGImage: cImage)
    
            return coloredImage
    
        } else {
            return nil
        } 
     }
    }
    

    Call like this:

    let image = UIImage(named: "your_image_name")
    testImage.image =  image?.maskWithColor(color: UIColor.blue)
    

提交回复
热议问题