Created
September 10, 2012 10:54
-
-
Save jlcampana/3690295 to your computer and use it in GitHub Desktop.
Locate first transparent pixel on a UIImage
This file contains hidden or 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
+ (CGPoint)getFirstTransparentPixelOfImage:(UIImage*)image | |
{ | |
int xx = 0; | |
int yy = 0; | |
int count = image.size.width * image.size.height; | |
// First get the image into your data buffer | |
CGImageRef imageRef = [image CGImage]; | |
NSUInteger width = CGImageGetWidth(imageRef); | |
NSUInteger height = CGImageGetHeight(imageRef); | |
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); | |
unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char)); | |
NSUInteger bytesPerPixel = 4; | |
NSUInteger bytesPerRow = bytesPerPixel * width; | |
NSUInteger bitsPerComponent = 8; | |
CGContextRef context = CGBitmapContextCreate(rawData, width, height, | |
bitsPerComponent, bytesPerRow, colorSpace, | |
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); | |
CGColorSpaceRelease(colorSpace); | |
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); | |
CGContextRelease(context); | |
CGPoint p = CGPointMake(width-1, height-1); | |
// Now your rawData contains the image data in the RGBA8888 pixel format. | |
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel; | |
for (int ii = 0 ; ii < count ; ++ii) | |
{ | |
CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0; | |
if (alpha>0.0) | |
{ | |
p.y = ii/width; | |
p.x = ii - p.y * width; | |
free(rawData); | |
return p; | |
} | |
byteIndex += 4; | |
} | |
free(rawData); | |
return p; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment