如何在Objective-C中使用UIImage作为遮罩

Phi*_*ton 19 core-graphics objective-c quartz-2d

我有一个全黑的UIImage,有一个alpha通道,所以有些部分是灰色的,有些部分是完全透明的.我希望将这些图像用作其他颜色的遮罩(让我们说白色以使其变得容易),因此最终产品现在是白色图像,其中部分透明.

我一直在四处寻找在苹果文档站点位置: http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_images/dq_images.html#//apple_ref/doc/uid/ TP30001066-CH212-CJBHIJEB

但我对Quartz/Core Graphics完全不熟悉,所以我不能真正理解这些例子.

有谁知道我可以用来查看一些完整代码示例的链接?

Jan*_*ano 51

在iOS 7+中你应该使用UIImageRenderingModeAlwaysTemplate.请参阅/sf/answers/1887589021/


从黑色与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;
}
Run Code Online (Sandbox Code Playgroud)

Ole Zorn的致谢:https://gist.github.com/1102091