Skip to content

Instantly share code, notes, and snippets.

@edwardean
Created January 30, 2016 15:08
Show Gist options
  • Select an option

  • Save edwardean/32c1ef21d7b732301242 to your computer and use it in GitHub Desktop.

Select an option

Save edwardean/32c1ef21d7b732301242 to your computer and use it in GitHub Desktop.
mask UIImage
#define Mask8(__x__) ((__x__) & 0xFF)
#define R(__x__) (Mask8(__x__))
#define G(__x__) (Mask8(__x__ >> 8))
#define B(__x__) (Mask8(__x__ >> 16))
#define A(__x__) (Mask8(__x__ >> 24))
#define __RGBA(r, g, b, a) (Mask8(r) | Mask8(g)<<8 | Mask8(b)<<16 | Mask8(a)<<24)
- (UIImage *)maskImage:(UIImage *)maskImage {
if (!maskImage) {
return self;
}
UInt32 *inputPixels;
UInt32 *maskPixels;
CGImageRef maskImageRef = [maskImage CGImage];
CGImageRef inputImageRef = [self CGImage];
NSUInteger inputWidth = CGImageGetWidth(inputImageRef);
NSUInteger inputHeight = CGImageGetHeight(inputImageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSUInteger bytesPerPixel = 4;
NSUInteger bitsPerComponent = 8;
NSUInteger inputBytesPerRow = bytesPerPixel * inputWidth;
inputPixels = (UInt32 *)calloc(inputHeight * inputWidth, sizeof(UInt32));
maskPixels = (UInt32 *)calloc(inputHeight * inputWidth, sizeof(UInt32));
CGContextRef context = CGBitmapContextCreate(inputPixels, inputWidth, inputHeight, bitsPerComponent, inputBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGContextDrawImage(context, CGRectMake(0, 0, inputWidth, inputHeight), inputImageRef);
CGContextRef maskContext = CGBitmapContextCreate(maskPixels, inputWidth, inputHeight, bitsPerComponent, inputBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGContextDrawImage(maskContext, CGRectMake(0, 0, inputWidth, inputHeight), maskImageRef);
for (NSUInteger i = 0; i<inputHeight; i++) {
for (NSUInteger j = 0; j<inputWidth; j++) {
UInt32 *currentPixel = inputPixels + (i*inputWidth)+j;
UInt32 *currentMaskPixel = maskPixels + (i * inputWidth)+j;
UInt32 color = *currentMaskPixel;
NSInteger alpha = A(color);
if (alpha != 0) {
*currentPixel = __RGBA(0, 0, 0, 0);
}
}
}
CGImageRef destImageRef = CGBitmapContextCreateImage(context);
UIImage *destImage = [UIImage imageWithCGImage:destImageRef];
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);
CGContextRelease(maskContext);
free(inputPixels);
free(maskPixels);
return destImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment