- (CGRect)cropRectForImage:(UIImage *)image {CGImageRef cgImage = image.CGImage;CGContextRef context = [self createARGBBitmapContextFromImage:cgImage];if (context == NulL) return CGRectZero; size_t wIDth = CGImageGetWIDth(cgImage);size_t height = CGImageGetHeight(cgImage);CGRect rect = CGRectMake(0,wIDth,height);CGContextDrawImage(context,rect,cgImage);unsigned char *data = CGBitmapContextGetData(context);CGContextRelease(context);//Filter through data and look for non-transparent pixels.int lowX = wIDth;int lowY = height;int highX = 0;int highY = 0;if (data != NulL) { for (int y=0; y<height; y++) { for (int x=0; x<wIDth; x++) { int pixelindex = (wIDth * y + x) * 4 /* 4 for A,R,G,B */; if (data[pixelindex] != 0) { //Alpha value is not zero; pixel is not transparent. if (x < lowX) lowX = x; if (x > highX) highX = x; if (y < lowY) lowY = y; if (y > highY) highY = y; } } } free(data);} else { return CGRectZero;}return CGRectMake(lowX,lowY,highX-lowX,highY-lowY);}
创建位图上下文的方法:
- (CGContextRef)createARGBBitmapContextFromImage:(CGImageRef)inImage {CGContextRef context = NulL;CGcolorSpaceRef colorSpace;voID *bitmapData;int bitmapByteCount;int bitmapBytesPerRow;// Get image wIDth,height. We'll use the entire image.size_t wIDth = CGImageGetWIDth(inImage);size_t height = CGImageGetHeight(inImage);// Declare the number of bytes per row. Each pixel in the bitmap in this// example is represented by 4 bytes; 8 bits each of red,green,blue,and// Alpha.bitmapBytesPerRow = (wIDth * 4);bitmapByteCount = (bitmapBytesPerRow * height);// Use the generic RGB color space.colorSpace = CGcolorSpaceCreateDeviceRGB();if (colorSpace == NulL) return NulL;// Allocate memory for image data. This is the destination in memory// where any drawing to the bitmap context will be rendered.bitmapData = malloc( bitmapByteCount );if (bitmapData == NulL){ CGcolorSpaceRelease(colorSpace); return NulL;}// Create the bitmap context. We want pre-multiplIEd ARGB,8-bits// per component. Regardless of what the source image format is// (CMYK,Grayscale,and so on) it will be converted over to the format// specifIEd here by CGBitmapContextCreate.context = CGBitmapContextCreate (bitmapData,height,8,// bits per component bitmapBytesPerRow,colorSpace,kCGImageAlphaPremultiplIEdFirst);if (context == NulL) free (bitmapData);// Make sure and release colorspace before returningCGcolorSpaceRelease(colorSpace);return context;}
最后,从返回的CGRect中获得新的UIImage:
CGRect newRect = [self cropRectForImage:oldImage];CGImageRef imageRef = CGImageCreateWithImageInRect(oldImage.CGImage,newRect);UIImage *newImage = [UIImage imageWithCGImage:imageRef];CGImageRelease(imageRef);
我从this very useful article获得了一点代码.希望它有帮助!
总结以上是内存溢出为你收集整理的ios – 如何自动裁剪UIImage?全部内容,希望文章能够帮你解决ios – 如何自动裁剪UIImage?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)