Created
September 10, 2012 11:16
-
-
Save jlcampana/3690379 to your computer and use it in GitHub Desktop.
Locate the most left non transparent pixel of 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)getMostLeftTransparentPixelOfImage:(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) | |
{ | |
CGPoint p2; | |
p2.y = ii/width; | |
p2.x = ii - p2.y * width; | |
if (p2.x<p.x) | |
{ | |
p = p2; | |
} | |
} | |
byteIndex += 4; | |
} | |
free(rawData); | |
return p; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment