如何在 UIImage 上像 UIButton 一样在点击时实现突出显示?

How to implement highlighting on UIImage like UIButton does when tapped?(如何在 UIImage 上像 UIButton 一样在点击时实现突出显示?)
本文介绍了如何在 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 一样在点击时实现突出显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to stop UIBarButtonItem text from truncating?(如何阻止UIBarButtonItem文本被截断?)
java.lang.IllegalStateException: SimpleTypeImpl should not be created for error type(异常:不应为错误类型创建SimpleTypeImpl)
How to send an image with custom keyboard iOS(如何使用自定义键盘IO发送映像)
Android IllegalArgumentException: The tag for fragment_XXX is invalid. Received: layout-sw600dp/fragment_XXX_0(Android IlLegalArgumentException:Fragment_XXX的标签无效。收到:Layout-sw600dp/Fragment_XXX_0)
NSURLSessionTaskPriority seems to be ignored?(NSURLSessionTaskPriority似乎被忽略了?)
How to make dataWithEPSInsideRect vector rather than bitmap in vector format?(如何用EPSInside Rect将dataWithEPSInside Rect变成矢量而不是位图的矢量格式?)