本文介绍了如何在Objective-C中将UIImage用作颜色上的蒙版的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个全为黑色且带有alpha通道的UIImage,因此某些部分为灰色,而某些部分是完全透明的.我想将这些图像用作其他颜色的遮罩(假设使用白色可以使其变得容易),所以现在的最终产品是白色图像,其部分透明.

I have a UIImage that is all black with an alpha channel so some parts are grayish and some parts are completely see-through. I want to use that images as a mask over some other color (let's say white to make it easy), so the final product is now a white image with parts of it transparent.

我一直在这里的Apple文档站点中浏览: http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_images/dq_images.html#//apple_ref/doc/uid/TP30001066-CH212-CJBHIJEB

I've been looking around on the Apple documentation site here: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完全陌生,所以我不能真正理解这些示例.

But I'm completely new to Quartz/Core Graphics, so I don't can't really make sense of those examples.

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

Does anyone know of a link to some full code samples that I could use to look at?

推荐答案

在iOS 7以上版本中,您应该使用UIImageRenderingModeAlwaysTemplate.参见 https://stackoverflow.com/a/26965557/870313

In iOS 7+ you should use UIImageRenderingModeAlwaysTemplate instead. See https://stackoverflow.com/a/26965557/870313

从带有黑色字母的主图像(iOS)创建任意颜色的图标.

Creating arbitrarily-colored icons from a black-with-alpha master image (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

Credits to Ole Zorn: https://gist.github.com/1102091

这篇关于如何在Objective-C中将UIImage用作颜色上的蒙版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:38