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 ,裁剪圖片等。
