How to implement highlighting on UIImage like UIButton does when tapped?
Asked Answered
I

1

19

I need to replicate the effect that the UIButton does on an image when tapped, the highlighting. See:

alt text

The original PNG is a square with alpha background. When I set it as UIButton's image it automatically apply an effect on the non-alpha pixels of the image.

How to do this effect?

Inseparable answered 13/1, 2011 at 15:41 Comment(0)
R
49

You could achieve this with a simple category on UIImage:

@interface UIImage (Tint)

- (UIImage *)tintedImageUsingColor:(UIColor *)tintColor;

@end

@implementation UIImage (Tint)

- (UIImage *)tintedImageUsingColor:(UIColor *)tintColor {
  UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
  CGRect drawRect = CGRectMake(0, 0, self.size.width, self.size.height);
  [self drawInRect:drawRect];
  [tintColor set];
  UIRectFillUsingBlendMode(drawRect, kCGBlendModeSourceAtop);
  UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return tintedImage;
}

@end

For the effect shown above, you'd pass something like [UIColor colorWithWhite:0.0 alpha:0.3] as the tintColor parameter (experiment with the alpha value).

Retrogradation answered 13/1, 2011 at 20:25 Comment(4)
Unlike some other solutions floating around SO, this has the nice effect of not coloring the whole rect. Good use of UIRectFillUsingBlendMode()Argyle
Awesome. Finally found an answer to this. :) Thank you!Exercitation
For RETINA display support: UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);Neral
Using self.scale would be better here.Retrogradation

© 2022 - 2024 — McMap. All rights reserved.