我们的需求是获取图片的透明区域
<p><code>- (UIImage *)crateImage:(UIImage *)image{
CGImageRef cgimage = [image CGImage];
size_t width = CGImageGetWidth(cgimage); // 图片宽度
size_t height = CGImageGetHeight(cgimage); // 图片高度
unsigned char *data = calloc(width * height * 4, sizeof(unsigned char)); // 取图片首地址
size_t bitsPerComponent = 8; // r g b a 每个component bits数目
size_t bytesPerRow = width * 4; // 一张图片每行字节数目 (每个像素点包含r g b a 四个字节)
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB(); // 创建rgb颜色空间
CGContextRef context =
CGBitmapContextCreate(data,
width,
height,
bitsPerComponent,
bytesPerRow,
space,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), cgimage);
NSMutableArray *xArr = [[NSMutableArray alloc]init];
NSMutableArray *yArr = [[NSMutableArray alloc]init];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for (size_t i = 0; i < height; i++)
{
for (size_t j = 0; j < width; j++)
{
size_t pixelIndex = i * width * 4 + j * 4;
int alpha = data[pixelIndex];
int red = data[pixelIndex+1];
int green = data[pixelIndex + 2];
int blue = data[pixelIndex + 3];
UIColor *color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:
(blue/255.0f) alpha:(alpha/255.0f)];
UIColor *color1 = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.00];
if ([self isTheSameColor2:color anotherColor:color1]) {
int x = (int) j;
int y = (int) i;
[xArr addObject:[NSNumber numberWithInt:x]];
[yArr addObject:[NSNumber numberWithInt:y]];
}
}
}
int xBig = [[xArr valueForKeyPath:@"@max.intValue"] intValue];
int xMin = [[xArr valueForKeyPath:@"@min.intValue"] intValue];;
NSLog(@"Xmax = %d Xmin = %d",xBig,xMin);
self->maxX = xBig;
self->minX = xMin;
int yBig = [[yArr valueForKeyPath:@"@max.intValue"] intValue];
int yMin = [[yArr valueForKeyPath:@"@min.intValue"] intValue];
self->maxY = yBig;
self->minY = yMin;
NSLog(@"Ymax = %d Ymin = %d",yBig,yMin);
dispatch_async(dispatch_get_main_queue(), ^{
[self createPic];
});
});
cgimage = CGBitmapContextCreateImage(context);
image = [UIImage imageWithCGImage:cgimage];
return image;
}
- (BOOL) isTheSameColor2:(UIColor)color1 anotherColor:(UIColor)color2
{
if (CGColorEqualToColor(color1.CGColor, color2.CGColor))
{
return YES;
}
else
{
return NO;
}
}</code></p>