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

回眸只為那壹抹淺笑 提交于 2019-11-27 09:26:23

问题


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

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?


回答1:


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).



来源:https://stackoverflow.com/questions/4681903/how-to-implement-highlighting-on-uiimage-like-uibutton-does-when-tapped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!