Search code examples
iosafnetworking-2

imageWithRenderingMode doesn't work with setImageWithUrl (for tintColor)


I can tint a UIImage in a UIImageView using :

imageView = [[UIImageView alloc]initWithImage:[myImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]];
imageView.tintColor = [UIColor redColor];

But when the image is initialized with AFNetworking's setImageWithUrl :

imageView = [imageView setImageWithUrl:url];
imageView.image = [imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
imageView.tintColor = [UIColor redColor];

This has no effect, the image is displayed with original colors.

Tested on iOS 7+.


Solution

  • Your code has no effect because you are assigning the image to be fetched from the remote URL, which takes time and thus happens later - after your code has finished. Thus, this line does nothing:

    imageView.image = [imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    

    ...because, at the time it runs, imageView.image is still nil.

    Instead, use a networking command with a completion handler, and don't change the image rendering mode until the completion handler. In particular, what I would do is: First, download the image. Now (in the completion handler) derive the template image and assign it to the image view.

    EDIT:

    Another problem, based on your later comments, is that you seem not to understand what an image view is. It holds one image - the most recently assigned image. So your code is now behaving exactly as I would expect - the image view is displaying the template image, because that is the last image you assigned to it.

    imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate colors the non-transparent parts of the original image the tint color and that's all - and that is exactly what you are now seeing, so your code is working.