Skip to content

Instantly share code, notes, and snippets.

@hollance
Created June 15, 2012 12:42
Show Gist options
  • Save hollance/2936287 to your computer and use it in GitHub Desktop.
Save hollance/2936287 to your computer and use it in GitHub Desktop.
Drawing inner glow with Core Graphics
- (CGImageRef)createMaskFromAlphaChannel:(UIImage *)image
{
size_t width = image.size.width;
size_t height = image.size.height;
NSMutableData *data = [NSMutableData dataWithLength:width*height];
CGContextRef context = CGBitmapContextCreate(
[data mutableBytes], width, height, 8, width, NULL, kCGImageAlphaOnly);
// Set the blend mode to copy to avoid any alteration of the source data
CGContextSetBlendMode(context, kCGBlendModeCopy);
// Draw the image to extract the alpha channel
CGContextDrawImage(context, CGRectMake(0.0, 0.0, width, height), image.CGImage);
CGContextRelease(context);
CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFMutableDataRef)data);
CGImageRef maskingImage = CGImageMaskCreate(width, height, 8, 8, width, dataProvider, NULL, TRUE);
CGDataProviderRelease(dataProvider);
return maskingImage;
}
- (void)drawRect:(CGRect)rect
{
UIImage *image = [UIImage imageNamed:@"TheImage"];
CGRect imageRect = CGRectMake(10, 10, image.size.width, image.size.height);
CGContextRef context = UIGraphicsGetCurrentContext();
// Draw black background
CGContextSetRGBFillColor(context, 0.0f, 0.0f, 0.0f, 1.0f);
CGContextFillRect(context, rect);
// Adjust for different coordinate systems from UIKit and Core Graphics
CGContextTranslateCTM(context, 0.0f, self.bounds.size.height);
CGContextScaleCTM(context, 1.0f, -1.0f);
// Draw the original image
CGContextDrawImage(context, imageRect, image.CGImage);
CGContextSaveGState(context);
// Clip to the original image, so that we only draw the shadows on the
// inside of the image but nothing outside.
CGContextClipToMask(context, imageRect, image.CGImage);
// Set up the shadow
UIColor *innerGlowColor = [UIColor colorWithRed:1.0f green:1.0f blue:1.0f alpha:1.0f];
CGContextSetShadowWithColor(context, CGSizeZero, 2, innerGlowColor.CGColor);
// Create a mask with an inverted alpha channel and draw it. This will
// cause the shadow to appear on the inside of our original image.
CGImageRef mask = [self createMaskFromAlphaChannel:image];
CGContextDrawImage(context, imageRect, mask);
CGImageRelease(mask);
CGContextRestoreGState(context);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment