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
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.
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
And after running above code (exp: TintColor
is RED). We have:
SO: how your image is depends on how you designed it
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With