我想创建一个 CoreImage 过滤器链,并能够通过将其单独的效果与 alpha 或不透明度设置合成来控制链中每个过滤器的“强度”,但我没有看到与 alpha 合成的方法或文档中的不透明度。
我想我可以跳出核心图像过滤器链并与核心图形上下文合成。
我想创建一个 CoreImage 过滤器链,并能够通过将其单独的效果与 alpha 或不透明度设置合成来控制链中每个过滤器的“强度”,但我没有看到与 alpha 合成的方法或文档中的不透明度。
我想我可以跳出核心图像过滤器链并与核心图形上下文合成。
CIColorMatrix过滤器可用于更改 CIImage 的 alpha 分量,然后您可以将其合成到背景图像上:
CIImage *overlayImage = … // from file, CGImage etc
CIImage *backgroundImage = … // likewise
CGFloat alpha = 0.5;
CGFloat rgba[4] = {0.0, 0.0, 0.0, alpha};
CIFilter *colorMatrix = [CIFilter filterWithName:@"CIColorMatrix"];
[colorMatrix setDefaults];
[colorMatrix setValue:overlayImage forKey: kCIInputImageKey];
[colorMatrix setValue:[CIVector vectorWithValues:rgba count:4] forKey:@"inputAVector"];
CIFilter *composite = [CIFilter filterWithName:@"CISourceOverCompositing"];
[composite setDefaults];
[composite setValue:colorMatrix.outputImage forKey: kCIInputImageKey];
[composite setValue:backgroundImage forKey: kCIInputBackgroundImageKey];
UIImage *blendedImage = [UIImage imageWithCIImage:composite.outputImage];
mrwalker 提供了一个很好的答案,我将其转换为 Swift。
let sourceImage: CIImage = ...
// This is where I get the overlayImage, and intensity is alpha, used later
guard let ciFilter = LUTBuilder.getCIFilter(from: filter.filter), let intensity = filter.intensity else { return CIImage() }
ciFilter.setValue(sourceImage.clampedToExtent(), forKey: kCIInputImageKey)
let overlayImage = ciFilter.outputImage!.cropped(to: sourceImage.extent)
let alpha = CGFloat(intensity)
let rgba = [0.0, 0.0, 0.0, alpha]
guard
let colorMatrix = CIFilter(name: "CIColorMatrix"),
let composite = CIFilter(name: "CISourceOverCompositing")
else { return CIImage() }
colorMatrix.setDefaults()
colorMatrix.setValue(overlayImage, forKey: kCIInputImageKey)
colorMatrix.setValue(CIVector(values: rgba, count: 4), forKey: "inputAVector")
composite.setDefaults()
composite.setValue(colorMatrix.outputImage, forKey: kCIInputImageKey)
composite.setValue(sourceImage, forKey: kCIInputBackgroundImageKey)
return composite.outputImage ?? CIImage()
就这样搞定了。此答案中的代码:https ://stackoverflow.com/a/3188761/1408546
UIImage *bottomImage = inputImage;
UIImage *image = filterOutput;
CGSize newSize = CGSizeMake(inputImage.size.width, inputImage.size.height);
UIGraphicsBeginImageContext( newSize );
[bottomImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height) blendMode:kCGBlendModeNormal alpha:_opacity];
UIImage *blendedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();