objective-c - 如何在 Objective-C 中使用 UIImage 作为颜色的 mask

标签 objective-c core-graphics quartz-2d

我有一个全黑的带有 alpha channel 的 UIImage,所以有些部分是灰色的,有些部分是完全透明的。我想将这些图像用作其他颜色的 mask (为了简单起见,我们假设为白色),因此最终产品现在是一个白色图像,其中的一部分是透明的。

我一直在 Apple 文档网站上四处寻找: https://developer.apple.com/library/archive/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_images/dq_images.html#//apple_ref/doc/uid/TP30001066-CH212-CJBHIJEB

但我并不能真正理解这些例子。

最佳答案

在 iOS 7+ 中,您应该改用 UIImageRenderingModeAlwaysTemplate。参见 https://stackoverflow.com/a/26965557/870313


从带有 alpha 的黑色主图像 (iOS) 创建任意颜色的图标。

// Usage: UIImage *buttonImage = [UIImage ipMaskedImageNamed:@"UIButtonBarAction.png" color:[UIColor redColor]];

+ (UIImage *)ipMaskedImageNamed:(NSString *)name color:(UIColor *)color
{
    UIImage *image = [UIImage imageNamed:name];
    CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, image.scale);
    CGContextRef c = UIGraphicsGetCurrentContext();
    [image drawInRect:rect];
    CGContextSetFillColorWithColor(c, [color CGColor]);
    CGContextSetBlendMode(c, kCGBlendModeSourceAtop);
    CGContextFillRect(c, rect);
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

感谢 Ole Zorn:https://gist.github.com/1102091

关于objective-c - 如何在 Objective-C 中使用 UIImage 作为颜色的 mask ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6823493/

相关文章:

objective-c - 在 Cocoa 类中使用核心音频

c - C 或 Obj-C 中的隐写术库

ios - 多个 UIBezierPath 的渐变

ios - 创建 CGPathRef 的轮廓

iphone - CGContextClipToMask 在内部是如何工作的?

ios - 如何更改 iCarousel 库的包装属性?

ios - 在从 UIPickerView 选择的 NSTimer 的 UILabel 中显示秒数

iphone - 如何在 iPad 中获取实际的 pdf 页面大小?

objective-c - 在 UIImage 中顺序移动方 block

iphone - CALayer 阴影和半透明 UINavigationBars