我正在使用相机(iOS 7
,iPad mini
)拍摄照片并将其裁剪为正方形。我对以下代码中的默认裁剪功能非常满意:
imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
imagePickerController.mediaTypes = @[(NSString *) kUTTypeImage];
imagePickerController.allowsEditing = YES;
UIImage *image = info[UIImagePickerControllerEditedImage]
它给我一个方形叠加在我拍摄的图像上。如果我放大,我可以稍微平移图像。但是我很惊讶我无法上下移动图像(没有缩放)将裁剪矩形移动到图像上。如果我尝试这样做,它会反弹回原来的位置。我错过了什么?或者这个功能是否缺失?
从这里的许多问题来看,大多数问题的答案令人失望,而且必须以自定义方式完成。
答案 0 :(得分:1)
这是最简单的方法(没有重新实现UIImagePickerController)。首先,使用叠加使相机字段看起来是方形的。以下是3.5英寸屏幕的示例(您需要将其更新为适用于iPhone 5):
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.sourceType = source;
if (source == UIImagePickerControllerSourceTypeCamera) {
//Create camera overlay
CGRect f = imagePickerController.view.bounds;
f.size.height -= imagePickerController.navigationBar.bounds.size.height;
CGFloat barHeight = (f.size.height - f.size.width) / 2;
UIGraphicsBeginImageContext(f.size);
[[UIColor colorWithWhite:0 alpha:.5] set];
UIRectFillUsingBlendMode(CGRectMake(0, 0, f.size.width, barHeight), kCGBlendModeNormal);
UIRectFillUsingBlendMode(CGRectMake(0, f.size.height - barHeight, f.size.width, barHeight), kCGBlendModeNormal);
UIImage *overlayImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *overlayIV = [[UIImageView alloc] initWithFrame:f];
overlayIV.image = overlayImage;
[imagePickerController.cameraOverlayView addSubview:overlayIV];
}
imagePickerController.delegate = self;
[self presentViewController:imagePickerController animated:YES completion:nil];
然后,在您从UIImagePickerController获取图片后,将其裁剪为方形,如下所示:
//Crop the image to a square
CGSize imageSize = image.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
if (width != height) {
CGFloat newDimension = MIN(width, height);
CGFloat widthOffset = (width - newDimension) / 2;
CGFloat heightOffset = (height - newDimension) / 2;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(newDimension, newDimension), NO, 0.);
[image drawAtPoint:CGPointMake(-widthOffset, -heightOffset)
blendMode:kCGBlendModeCopy
alpha:1.];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
这是Objective c Code。