7

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.

dwlz
  • 9,793
  • 6
  • 46
  • 76
Mr Wolf
  • 4,766
  • 15
  • 55
  • 91

2 Answers2

22

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];
mrwalker
  • 1,783
  • 18
  • 23
-4

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();
Community
  • 1
  • 1
Mr Wolf
  • 4,766
  • 15
  • 55
  • 91
  • If you switch between Core Image and Core Graphics, you move between using the GPU and CPU for drawing. There are performance costs of doing this. In general, if you stay on the GPU as much as possible (and minimize switching) you'll get better performance for these kinds of drawing/compositing tasks. – fattjake Dec 03 '20 at 18:26