Skip to content

Instantly share code, notes, and snippets.

@jlcampana
Created September 10, 2012 10:54
Show Gist options
  • Save jlcampana/3690295 to your computer and use it in GitHub Desktop.
Save jlcampana/3690295 to your computer and use it in GitHub Desktop.
Locate first transparent pixel on a UIImage
+ (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