How can I color a UIImage in Swift?

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

    Add extension Function:

    extension UIImageView {
        func setImage(named: String, color: UIColor) {
            self.image = #imageLiteral(resourceName: named).withRenderingMode(.alwaysTemplate)
            self.tintColor = color
        }
    }
    

    Use like:

    anyImageView.setImage(named: "image_name", color: .red)
    
    0 讨论(0)
  • 2020-11-29 19:08

    Swift 3 extension wrapper from @Nikolai Ruhe answer.

    extension UIImageView {
    
        func maskWith(color: UIColor) {
            guard let tempImage = image?.withRenderingMode(.alwaysTemplate) else { return }
            image = tempImage
            tintColor = color
        }
    
    }
    

    It can be use for UIButton as well, e.g:

    button.imageView?.maskWith(color: .blue)
    
    0 讨论(0)
  • 2020-11-29 19:08

    Swift 4.

    Use this extension to create a solid colored image

    extension UIImage {   
    
        public func coloredImage(color: UIColor) -> UIImage? {
            return coloredImage(color: color, size: CGSize(width: 1, height: 1))
        }
    
        public func coloredImage(color: UIColor, size: CGSize) -> UIImage? {
    
            UIGraphicsBeginImageContextWithOptions(size, false, 0)
    
            color.setFill()
            UIRectFill(CGRect(origin: CGPoint(), size: size))
    
            guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
            UIGraphicsEndImageContext()
    
            return image
        }
    }
    
    0 讨论(0)
  • 2020-11-29 19:12

    There's a built in method to obtain a UIImage that is automatically rendered in template mode. This uses a view's tintColor to color the image:

    let templateImage = originalImage.imageWithRenderingMode(UIImageRenderingModeAlwaysTemplate)
    myImageView.image = templateImage
    myImageView.tintColor = UIColor.orangeColor()
    
    0 讨论(0)
  • 2020-11-29 19:12

    First you have to change the rendering property of the image to "Template Image" in the .xcassets folder. You can then just change the tint color property of the instance of your UIImageView like so:

    imageView.tintColor = UIColor.whiteColor()
    

    0 讨论(0)
  • 2020-11-29 19:14

    For iOS13+ there are withTintColor(__:) and withTintColor(_:renderingMode:) methods.

    Example usage:

    let newImage = oldImage.withTintColor(.red)
    

    or

    let newImage = oldImage.withTintColor(.red, renderingMode: .alwaysTemplate)
    
    0 讨论(0)
提交回复
热议问题