15

我正在尝试创建像 Instagram 这样的相机,用户可以在其中看到一个框,并且图像会裁剪到该框。出于某种原因,相机并没有一直走到屏幕底部,而是在接近尾声时切断。我还想知道如何将图像裁剪为恰好在该正方形内的 320x320?

在此处输入图像描述

4

2 回答 2

38

这是最简单的方法(无需重新实现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();
}

你完成了。

于 2013-07-18T01:41:06.883 回答
4

@Anders 的答案在 iPhone 5 上对我来说非常接近正确。我进行了以下修改,为 iPhone 5 添加了硬编码的覆盖:

CGRect f = imagePickerController.view.bounds;
f.size.height -= imagePickerController.navigationBar.bounds.size.height;
UIGraphicsBeginImageContext(f.size);
[[UIColor colorWithWhite:0 alpha:.5] set];
UIRectFillUsingBlendMode(CGRectMake(0, 0, f.size.width, 124.0), kCGBlendModeNormal);
UIRectFillUsingBlendMode(CGRectMake(0, 444, f.size.width, 52), kCGBlendModeNormal);
UIImage *overlayImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImageView *overlayIV = [[UIImageView alloc] initWithFrame:f];
overlayIV.image = overlayImage;
overlayIV.alpha = 0.7f;
[imagePickerController setCameraOverlayView:overlayIV];`

我希望这可以帮助别人。

于 2013-12-16T08:25:04.013 回答