How to apply a tintColor to a UIImage?

uiimage replace color
swiftui image tint color
uiimage background color
set tint color for image
set tint color swift
uiimagerenderingmodealwaystemplate
swift 5 tint uiimage
apply color to image swift

I have a UIImage that is a small symbol that is all black. The UIImage is getting set in a custom UIButton subclass I have. Is it possible to have the image to apply the tintColor to it, so instead of the black image it changes colors to whatever the tintColor is?

I'm just trying to avoid creating new assets.

// here I want defaultImageName (that is black) to use the tintColor (that is white)
[self setImage:[UIImage imageNamed:defaultImageName] forState:UIControlStateNormal];

If you are just supporting iOS 7 you can use tintColor and UIImageRenderingModeAlwaysTemplate

This article covers that:

https://www.captechconsulting.com/blogs/ios-7-tutorial-series-tint-color-and-easy-app-theming

If you need to support an earlier version you may want to consider this thread

How would I tint an image programmatically on the iPhone?

How can I color a UIImage in Swift?, fill(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } } How to use self.imgVw.​image =  The default is nil.If a non-nil value is specified, the color is applied to any template images attached to the image view.For more information, see the rendering Mode property on the UIImage class.

Swift 4, copy-paste solution

@IBOutlet weak var iconImageView: UIImageView!
iconImageView.image = UIImage(imageLiteralResourceName: "myImageName").withRenderingMode(.alwaysTemplate)
iconImageView.tintColor = UIColor.red

withTintColor(_:), Declaration. func withTintColor(_ color: UIColor) -> UIImage. Parameters. color. The tint color to apply to the image. Return Value. A new version of the image  The easiest way to apply a tint to an UIImageView image is to set the imageWithRenderingMode of the image to AlwayTemplate and then apply a tint. This only takes two lines of code to get the desired results. The below snippet shows how to turn the UIImageView image blue.

Here's how I use tint colors and opacities in IOS 9 with Swift -

//apply a color to an image
//ref - http://stackoverflow.com/questions/28427935/how-can-i-change-image-tintcolor
//ref - https://www.captechconsulting.com/blogs/ios-7-tutorial-series-tint-color-and-easy-app-theming
func getTintedImage() -> UIImageView {

    var image :UIImage
    var imageView :UIImageView

    image = UIImage(named: "someAsset")!
    let size  : CGSize = image.size
    let frame : CGRect = CGRectMake((UIScreen.mainScreen().bounds.width-86)/2, 600, size.width, size.height)

    let redCover : UIView = UIView(frame: frame)

    redCover.backgroundColor = UIColor.redColor()
    redCover.layer.opacity = 0.75

    imageView = UIImageView();
    imageView.image = image.imageWithRenderingMode(UIImageRenderingMode.Automatic)

    imageView.addSubview(redCover)

    return imageView
}

Change image tint color programmatically in swift , How do I change the color of my tint in Swift? iOS 12 does have a TintColor that can be applied while rendering into a UIImageView, but I don't see a way to use that when drawing programmatically into a UIImage: // Apply tint color. UIImageView Control.

Why not use image filtering

btn.setImage(image, for: UIControl.State.normal)
btn.setImage(image.disabled, for: UIControl.State.disabled)

Use CoreImage to do image filter

extension UIImage
{
    /// Create a grayscale image with alpha channel. Is 5 times faster than grayscaleImage().
    /// - Returns: The grayscale image of self if available.
    var disabled: UIImage?
    {
        // Create image rectangle with current image width/height * scale
        let pixelSize = CGSize(width: self.size.width * self.scale, height: self.size.height * self.scale)
        let imageRect = CGRect(origin: CGPoint.zero, size: pixelSize)
        // Grayscale color space
         let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceGray()

            // Create bitmap content with current image size and grayscale colorspace
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
        if let context: CGContext = CGContext(data: nil, width: Int(pixelSize.width), height: Int(pixelSize.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
            {
                // Draw image into current context, with specified rectangle
                // using previously defined context (with grayscale colorspace)
                guard let cg = self.cgImage else{
                    return nil
                }
                context.draw(cg, in: imageRect)
                // Create bitmap image info from pixel data in current context
                if let imageRef: CGImage = context.makeImage(){
                    let bitmapInfoAlphaOnly = CGBitmapInfo(rawValue: CGImageAlphaInfo.alphaOnly.rawValue)

                    guard let context = CGContext(data: nil, width: Int(pixelSize.width), height: Int(pixelSize.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfoAlphaOnly.rawValue) else{
                        return nil
                    }
                    context.draw(cg, in: imageRect)
                    if let mask: CGImage = context.makeImage() {
                        // Create a new UIImage object
                        if let newCGImage = imageRef.masking(mask){
                            // Return the new grayscale image
                            return UIImage(cgImage: newCGImage, scale: self.scale, orientation: self.imageOrientation)
                        }
                    }

                }
            }


        // A required variable was unexpected nil
        return nil
    }
}

Of course, in Swift 5

tintColor, specified, the color is applied to any template images attached to the image view. For more information, see the renderingMode property on the UIImage class. let image = UIImage(named:"your image name")?.imageWithRenderingMode(.AlwaysTemplate) let yourimageView.tintColor = UIColor.redColor() yourimageView.image = image In swift 3.0 you can use this let image = UIImage(named:"your image name")?.withRenderingMode(.alwaysTemplate) let yourimageView.tintColor = UIColor.red yourimageView.image = image

Use this simple extension to UIImageView

@IBInspectable var tintedColor: UIColor{
    get{
        return tintColor
    }
    set{
        image = image?.withRenderingMode(.alwaysTemplate)
        tintColor = newValue
    }
}

tintColor, The tint color of a UIImageView is the standard iOS 7 blue by default, but you can change it easily enough: imageView.tintColor = UIColor.red. Just add a new runtime attribute which will set the tintColor of the UIImageView to the specified color and ensure the image is tinted. You will still need to set your image to be rendered as a template image in your Images.xcassets file. This way you dont need any additional outlets, extensions or lines of code.

How to recolor UIImages using template images and , UIImageView does. This little method returns a UIImage, tinted with a UIColor. It's useful for things like table icons, where the image view is read  If you use PNG images (as i think because of icons) - just use: let originalImage = UIImage(named: "iconName") let tintedImage = originalImage?.withRenderingMode(.alwaysTemplate) yourButton.setImage(tintedImage, forState: .normal) yourButton.tintColor = UIColor.blue //change color of icon

UIImage doesn't have a tint colour. UIImageView does. This little , In this post I will discuss how you can apply a tint to an UIImageView image. The example I will use to show the image tint is to toggle on and off  To then set the tint color in Swift 3 or 4: theImage.setTintColor(UIColor.red) Swift 2: theImage.setTintColor(UIColor.redColor()) To then set the tint color in Objective-C: [self.theImage setTintColor:[UIColor redColor]]; If you use a template image and do not apply a tint colour, the Global Tint for your WatchKit app will be applied.

How to tint an UIImageView Image, using template images and using a UIImageView with a tintColor change, however sometimes this isn't feasible. We can use our icons along  All subclasses of UIView derive their behavior for tint Color from the base class. See the discussion of tint Color at the UIView level for more information. This property has no default effect for buttons with type UIButton.Button Type.custom. For custom buttons, you must implement any behavior related to tint Color yourself.

Comments
  • This isn't a duplicate of the linked question.
  • please see this link change image tintColor in iOS and WatchKit
  • Please note that using templates might impact performance since it is always composited on the fly
  • You need to setup your UIImage so it draws the image as a template image, ignoring its color information: UIImage *image = [[UIImage imageNamed:@"image.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];. And then the tint color will be applied, set that on your UIImageView: _imageView.tintColor = [UIColor whiteColor];
  • Unfortunately the first Llink is dead
  • WARNING: I would like to add that if you perform any task that returns a new image, you WILL need to set withRenderingMode(.alwaysTemplate) again. Example: if you use UIGraphicsImageRenderer to resize image. This also applies if you set an asset image to Template rendering mode.
  • I dislike this solution because it doesn't tint the image. Instead it reduces the contrast by using a second layer and making one of the (depends on z order) semi transparent. You also can never achieve a satisfying saturation of the tint color.
  • quite interesting. Please send over or post here some tips or url links to help me then generate and post here an alternative solution! :)