iOS 从相册取出的图片默认 取中间部分 裁剪成方形的
iOS 获取相册之后,图片是不规则的,想要默认取中间部分裁剪成方形,可以用下面方法,这是我自己工程中用到的,所以绝对可用。废话不多少,直接上代码:
转载请注明出处:http://www.cnblogs.com/shisishao/p/6000999.html
- (void)addImageModelToPostVCModelArray:(NSArray *)array { if (array && array.count > 0) { NSMutableArray *imageModelArray = [NSMutableArray array]; for (int i = 0; i < array.count; i++) { ZXCropImageModel *cropModel = [[ZXCropImageModel alloc] init]; UIImage *image = array[i]; NSValue *sizeValue = [NSValue valueWithCGSize:CGSizeMake(image.size.width, image.size.height)]; cropModel.sizeValue = sizeValue; CGRect rect = [self getImageRect:image]; UIImage *cropImage = [self getCropImage:image andRect:rect]; NSValue *rectValue = [NSValue valueWithCGRect:rect]; cropModel.rectValue = rectValue; cropModel.cropImage = cropImage; [imageModelArray addObject:cropModel]; } [self getPostEditModelArray:imageModelArray]; } } - (void)getPostEditModelArray:(NSArray *)imageModelArray { // 处理后的图片对象 } - (CGRect)getImageRect:(UIImage *)tempImage { CGRect rect; if (tempImage.size.width > tempImage.size.height) { rect = CGRectMake((tempImage.size.width-tempImage.size.height)/2, 0, tempImage.size.height, tempImage.size.height); } else if (tempImage.size.width < tempImage.size.height) { rect = CGRectMake(0, (tempImage.size.height-tempImage.size.width)/2, tempImage.size.width, tempImage.size.width); } else { rect = CGRectMake(0, 0, tempImage.size.width, tempImage.size.width); } return rect; } - (UIImage *)getCropImage:(UIImage *)image andRect:(CGRect)rect { rect = CGRectMake(ceilf(rect.origin.x), ceilf(rect.origin.y), ceilf(rect.size.width), ceilf(rect.size.height)); UIGraphicsBeginImageContext(rect.size); [image drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)]; UIImage *cropImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return cropImage; }
其中的 对象 ZXCropImageModel 为:
@interface ZXCropImageModel : NSObject @property (nonatomic, strong) UIImage *cropImage; // 裁剪后图片 @property (nonatomic, strong) NSValue *sizeValue; // 图片size @property (nonatomic, strong) NSValue *rectValue; // 裁剪之后图片的 在原图中 的 frame @end
处理之后,会返回原图大小,裁剪之后图片的在原图中的 frame ,裁剪图片等。