Last active
December 17, 2015 10:59
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface UIImageView (Mask) | |
- (void)applyMask:(NSString *)maskName; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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