Skip to content

Instantly share code, notes, and snippets.

@MattesGroeger
Last active December 17, 2015 10:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattesGroeger/5599383 to your computer and use it in GitHub Desktop.
Save MattesGroeger/5599383 to your computer and use it in GitHub Desktop.
With this category of `UIImageView` you can apply a mask (grey-scale jpg) onto a given image. The mask is then applied on that existing image. With this technique you can use 2 compressed JPG's (not transparent image + mask) rather than one big PNG file.
#import <Foundation/Foundation.h>
@interface UIImageView (Mask)
- (void)applyMask:(NSString *)maskName;
@end
#import "UIImageView+Mask.h"
#import "UIImage+ImageLoading.h"
@implementation UIImageView (Mask)
- (void)applyMask:(NSString *)maskName
{
CGImageRef imageRef = self.image.CGImage;
CGImageRef maskRef = [UIImage imageNamedUncached:maskName].CGImage;
CGImageRef mask = [self getMask:maskRef];
CGImageRef imageWithAlpha= [self convertToAlphaImage:imageRef];
CGImageRef finalImageRef = CGImageCreateWithMask(imageWithAlpha, mask);
self.image = [UIImage imageWithCGImage:finalImageRef];
}
- (CGImageRef)getMask:(CGImageRef)imageRef
{
return CGImageMaskCreate(CGImageGetWidth(imageRef),
CGImageGetHeight(imageRef),
CGImageGetBitsPerComponent(imageRef),
CGImageGetBitsPerPixel(imageRef),
CGImageGetBytesPerRow(imageRef),
CGImageGetDataProvider(imageRef), nil, YES);
}
- (CGImageRef)convertToAlphaImage:(CGImageRef)imageRef
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat width = CGImageGetWidth(imageRef);
CGFloat height = CGImageGetWidth(imageRef);
CGContextRef contextWithAlpha = CGBitmapContextCreate(nil, (size_t) width, (size_t) height, 8, (size_t) (4*width), colorSpace, kCGImageAlphaPremultipliedFirst);
CGContextDrawImage(contextWithAlpha, CGRectMake(0, 0, width, height), imageRef);
CGImageRef imageWithAlpha = CGBitmapContextCreateImage(contextWithAlpha);
CGColorSpaceRelease(colorSpace);
CGContextRelease(contextWithAlpha);
return imageWithAlpha;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment