Xcode: compositing with alpha using core image

2019-03-16 17:13发布

问题:

I'd like to create a CoreImage filter chain, and to be able to control the "intensity" of each filter in the chain by compositing its individual effect with alpha, or opacity settings, but I am not seeing a way to composite with alpha or opacity in the docs.

I could jump out of Core image filter chain and composite with a core graphics context I guess.

回答1:

The CIColorMatrix filter can be used to alter the alpha component of a CIImage, which you can then composite onto a background image:

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];


回答2:

Ended up doing it like this. Code from this answer: 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();