Skip to content

Instantly share code, notes, and snippets.

@iOSDigital
Created January 12, 2014 01:14
Show Gist options
  • Save iOSDigital/8379249 to your computer and use it in GitHub Desktop.
Save iOSDigital/8379249 to your computer and use it in GitHub Desktop.
UIImage doesn't have a tint colour. 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 only. Means you don't have to create loads of PNGs in different colours.
-(UIImage *)imageWithTint:(UIImage *)image andTintColor:(UIColor *)tintColor {
UIImage *imageNew = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
UIImageView *imageView = [[UIImageView alloc] initWithImage:imageNew];
imageView.tintColor = tintColor;
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 0.0);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return tintedImage;
}
@qubblr
Copy link

qubblr commented Nov 21, 2018

Swift 4:

extension UIImage {
  func tinted(color: UIColor) -> UIImage? {
    let image = self.withRenderingMode(.alwaysTemplate)
    let imageView = UIImageView(image: image)
    imageView.tintColor = color
    
    UIGraphicsBeginImageContext(image.size)
    if let context = UIGraphicsGetCurrentContext() {
      imageView.layer.render(in: context)
      let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
      return tintedImage
    } else {
      return self
    }
  }
}

@michalsrutek
Copy link

Improving @qubblr 's answer - using UIGraphicsBeginImageContext uses default scale factor of 1.0 and thus images can appear blurry on most phones.
Added UIGraphicsBeginImageContextWithOptions with scale factor of 0.0, which sets the scale factor to be equal to the device’s main screen.

Swift 5.1

extension UIImage {
    func tinted(color: UIColor) -> UIImage? {
        let image = withRenderingMode(.alwaysTemplate)
        let imageView = UIImageView(image: image)
        imageView.tintColor = color

        UIGraphicsBeginImageContextWithOptions(image.size, false, 0.0)
        if let context = UIGraphicsGetCurrentContext() {
            imageView.layer.render(in: context)
            let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return tintedImage
        } else {
            return self
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment