NSView apply grayscale transform filters

Need to apply an overall effect to your NSView? It’s pretty easy using QuartzCore filters. Here’s an example applying a grayscale effect first and then a gamma effect on top.

EDIT: You need to enable layer backing for this to work.

#import <QuartzCore/QuartzCore.h>

- (void)initWithFrame:(NSRect)frame
{
   self = [super initWithFrame:frame];
   if (self) {
      self.wantsLayer = YES;  // Enable layer backing.
   }
   return self;
}

- (void)addFilters 
{
   if (!_filtersAdded) {
        // Yes, apply grayscale filter
        CIFilter *filt = [CIFilter filterWithName:@"CIColorMonochrome"]; // CIImage
        [filt setDefaults];
        [filt setValue:[CIColor colorWithRed:.3 green:.3 blue:.3 alpha:1] forKey:@"inputColor"];
        CIFilter *filt2 = [CIFilter filterWithName:@"CIGammaAdjust"]; // CIImage
        [filt2 setDefaults];
        [filt2 setValue:[NSNumber numberWithFloat:0.3] forKey:@"inputPower"];    
        [self setContentFilters:[NSArray arrayWithObjects:filt, filt2, nil]];
    }
   else {
      [self setContentFilters:[NSArray array]];
   }

   _filtersAdded = !_filtersAdded;
}
About these ads

One thought on “NSView apply grayscale transform filters

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s