Applying CIFilter to CALayer

So, CI Filters are now available in iOS 5, and I'm trying to apply it to CALayer, the way you do it on a Mac . Here is my code:

CALayer *myCircle = [CALayer layer];
myCircle.bounds = CGRectMake(0,0,30,30);
myCircle.position = CGPointMake(100,100);
myCircle.cornerRadius = 15;
myCircle.borderColor = [UIColor whiteColor].CGColor;
myCircle.borderWidth = 2;
myCircle.backgroundColor = [UIColor whiteColor].CGColor;

CIFilter *blurFilter = [CIFilter filterWithName:@"CIDiscBlur"];
[blurFilter setDefaults];
[blurFilter setValue:[NSNumber numberWithFloat:5.0f] forKey:@"inputRadius"];
[myCircle setFilters:[NSArray arrayWithObjects:blurFilter, nil]];

[self.view.layer addSublayer:myCircle];

My white circle is perfectly drawn, but the filter is not applied. Any suggestions?

+5
source share
1 answer

Besides being CIDiskBlurunavailable (with iOS SDK 5.1) and what setFilters:seems unavailable, you can do the following:

Create a CIImage input from the contents of your layer:

CIImage *inputImage = [CIImage imageWithCGImage:(CGImageRef)(myCircle.contents)];`

Apply your filters and get the result in CGImageRef:

CIFilter *filter = [CIFilter filterWith...];// A filter that is available in iOS or a custom one :)
...
CIImage *outputImage = [filter outputImage];
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef cgimg = [context createCGImage:outputImage fromRect:[outputImage extent]];

Finally, set CGImageRef to the layer:

[myCircle setContents:(id)cgimg];

That should work :)

+6
source

All Articles