如何在 UIImage 上像 UIButton 一样在点击时实现突出显示? [英] How to implement highlighting on UIImage like UIButton does when tapped?

查看:16
本文介绍了如何在 UIImage 上像 UIButton 一样在点击时实现突出显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要复制 UIButton 在点击时对图像的效果,即突出显示.见:

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

原始 PNG 是一个带有 alpha 背景的正方形.当我将它设置为 UIButton 的图像时,它会自动对图像的非 alpha 像素应用效果.

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.

这个效果怎么做?

推荐答案

您可以通过 UIImage 上的简单类别来实现:

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

对于上面显示的效果,您需要传递类似 [UIColor colorWithWhite:0.0 alpha:0.3] 作为 tintColor 参数(使用 alpha 值进行实验).

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

这篇关于如何在 UIImage 上像 UIButton 一样在点击时实现突出显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆