我有一个全黑的带有 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/