Created
January 12, 2014 01:14
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(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; | |
} |
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
Swift 4: