【问题标题】:How to implement highlighting on UIImage like UIButton does when tapped?如何在 UIImage 上像 UIButton 一样在点击时实现突出显示?
【发布时间】:2011-06-08 14:08:33
【问题描述】:

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

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

这个效果怎么做?

【问题讨论】:

    标签: objective-c uiimage uibutton mask layer


    【解决方案1】:

    您可以通过 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 值进行实验)。

    【讨论】:

    • 与 SO 周围的其他一些解决方案不同,这具有不为整个矩形着色的良好效果。善用 UIRectFillUsingBlendMode()
    • 太棒了。终于找到了这个问题的答案。 :) 谢谢!
    • 对于 RETINA 显示支持:UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
    • 在这里使用self.scale会更好。
    猜你喜欢
    • 2018-03-14
    • 2013-07-05
    • 2017-05-20
    • 2019-11-30
    • 1970-01-01
    • 2014-03-10
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多