编辑
使用(简单)自定义 CIFilter 的解决方案。此方法仅适用于 OSX,因为 iOS 不支持自定义过滤器:
CIFilter 子类(或多或少是Apple 的 How-To的副本):
#import <QuartzCore/QuartzCore.h>
@interface MaskFilter : CIFilter {
CIImage *inputImage;
}
@end
@implementation MaskFilter
static CIKernel *maskFilterKernel = nil;
+ (void)initialize {
[CIFilter registerFilterName: @"MaskFilter"
constructor: (id)self
classAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
@"Mask Filter", kCIAttributeFilterDisplayName,
[NSArray arrayWithObjects:
kCICategoryColorAdjustment,
kCICategoryStillImage, kCICategoryInterlaced,
kCICategoryNonSquarePixels,nil], kCIAttributeFilterCategories,
nil]
];
}
+ (CIFilter *)filterWithName:(NSString *)name {
CIFilter *filter;
filter = [[self alloc] init];
return filter;
}
- (id)init {
if(maskFilterKernel == nil) {
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSString *code = [NSString stringWithContentsOfFile:[bundle pathForResource:@"MaskFilter" ofType: @"cikernel"] encoding:NSUTF8StringEncoding error:nil];
NSArray *kernels = [CIKernel kernelsWithString:code];
maskFilterKernel = [kernels objectAtIndex:0];
}
return [super init];
}
- (CIImage *)outputImage {
CISampler *src = [CISampler samplerWithImage: inputImage];
return [self apply:maskFilterKernel, src, kCIApplyOptionDefinition, [src definition], nil];
}
@end
完成所有工作的自定义内核(文件名:MaskFilter.cikernel)
kernel vec4 maskFilterKernel(sampler src)
{
vec4 t = sample(src, destCoord());
t.w = (t.x == 0.0 ? (t.y == 0.0 ? (t.z == 0.0 ? 0.0 : 1.0) : 1.0) : 1.0);
return t;
}
使用过滤器就像内置过滤器一样工作:
CIFilter *filter = [MaskFilter filterWithName:@"MaskFilter"];
[filter setValue:ciImage forKey:@"inputImage"];
CIImage *mask = [filter valueForKey: @"outputImage"];
添加一个参数来选择用作遮罩颜色的颜色应该没问题。
旧答案
使用内置的方法和类,我只能想出这个相当不雅的解决方案(它只使用 Core Image 过滤器):
// convert all colors so they are brighter or equal to 0.5, except black
CIFilter *binary = [CIFilter filterWithName:@"CIColorMatrix"];
[binary setValue:inputImage forKey:@"inputImage"];
[binary setValue:[CIVector vectorWithX:1 Y:1 Z:1 W:0] forKey:@"inputRVector"];
[binary setValue:[CIVector vectorWithX:1 Y:1 Z:1 W:0] forKey:@"inputGVector"];
[binary setValue:[CIVector vectorWithX:1 Y:1 Z:1 W:0] forKey:@"inputBVector"];
[binary setValue:[CIVector vectorWithX:0.49999 Y:0.49999 Z:0.49999 W:0] forKey:@"inputBiasVector"];
inputImage = [binary valueForKey:@"outputImage"];
// convert to black/white only colors
binary = [CIFilter filterWithName:@"CIColorPosterize"];
[binary setDefaults];
[binary setValue:inputImage forKey:@"inputImage"];
[binary setValue:@2 forKey:@"inputLevels"];
inputImage = [binary valueForKey:@"outputImage"];
// get mask
CIFilter *mask = [CIFilter filterWithName:@"CIMaskToAlpha"];
[mask setDefaults];
[mask setValue: inputImage forKey:@"inputImage"];