Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change image tintColor

I'm receiving image from a server, then based on a color chosen by the user, the image color will be changed.

I tried the following :

_sketchImageView.image = [_sketchImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; [_sketchImageView setTintColor:color]; 

i got the opposite of my goal (the white color outside UIImage is colored with the chosen color).

what is going wrong?

i need to do the same in this question,the provided solution doesn't solve my case. How can I change image tintColor in iOS and WatchKit

like image 636
user2168496 Avatar asked Feb 10 '15 09:02

user2168496


People also ask

How do I change the color of an image in swift 5?

The absolute simplest way to change colors of images (or icons in this case) is to use the SF Symbols where applicaple. This is a set of symbols Apple provides that can easily be used in your own app.


2 Answers

Try to generate new image for yourself

UIImage *newImage = [_sketchImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; UIGraphicsBeginImageContextWithOptions(image.size, NO, newImage.scale); [yourTintColor set]; [newImage drawInRect:CGRectMake(0, 0, image.size.width, newImage.size.height)]; newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();  _sketchImageView.image = newImage; 

And use it.

Good luck

======= UPDATE =======

This solution will only change color of all pixel's image.

Example: we have a book image: http://pngimg.com/upload/book_PNG2113.png

enter image description here

And after running above code (exp: TintColor is RED). We have:

enter image description here

SO: how your image is depends on how you designed it

like image 91
Tony Avatar answered Sep 21 '22 08:09

Tony


In Swift you can use this extension: [Based on @VietHung's objective-c solution]

Swift 5:

extension UIImage {       func imageWithColor(color: UIColor) -> UIImage? {         var image = withRenderingMode(.alwaysTemplate)         UIGraphicsBeginImageContextWithOptions(size, false, scale)         color.set()         image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))         image = UIGraphicsGetImageFromCurrentImageContext()!         UIGraphicsEndImageContext()         return image     } } 

Previous Swift version:

extension UIImage {     func imageWithColor(color: UIColor) -> UIImage? {         var image = imageWithRenderingMode(.AlwaysTemplate)         UIGraphicsBeginImageContextWithOptions(size, false, scale)         color.set()         image.drawInRect(CGRect(x: 0, y: 0, width: size.width, height: size.height))         image = UIGraphicsGetImageFromCurrentImageContext()         UIGraphicsEndImageContext()         return image     } } 
like image 38
Mejdi Lassidi Avatar answered Sep 22 '22 08:09

Mejdi Lassidi