根据UIView/CGRect的大小将图像裁剪为正方形

swi*_*ode 10 crop uiimage image-resizing ios cgrect

我有一个AVCaptureSession的实现,我的目标是让用户拍照并只保存红色方框边框内的图像部分,如下所示:

UIViewController与AVCaptureSession的实现

AVCaptureSession previewLayer(相机)从(0,0)(左上角)跨越到相机控制条的底部(包含快门的视图上方的条形图).我的导航栏和控制栏是半透明的,因此相机可以显示.

我正在使用[captureSession setSessionPreset:AVCaptureSessionPresetPhoto];以确保保存到相机胶卷的原始图像就像Apple的相机一样.

用户将能够以纵向,左右横向拍摄照片,因此裁剪方法必须考虑到这一点.

到目前为止,我已尝试使用此代码裁剪原始图像:

DDLogVerbose(@"%@: Image crop rect: (%f, %f, %f, %f)", THIS_FILE, self.imageCropRect.origin.x, self.imageCropRect.origin.y, self.imageCropRect.size.width, self.imageCropRect.size.height);

// Create new image context (retina safe)
UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.imageCropRect.size.width, self.imageCropRect.size.width), NO, 0.0);

// Create rect for image
CGRect rect = self.imageCropRect;

// Draw the image into the rect
[self.captureManager.stillImage drawInRect:rect];

// Saving the image, ending image context
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
Run Code Online (Sandbox Code Playgroud)

然而,当我看到相机胶卷中的裁剪图像时,似乎它刚刚压缩了原始图像,而不是像我想的那样丢弃图像的顶部和底部.它还会在"裁剪"图像的顶部产生53像素的空白区域,这可能是因为我的y位置CGRect.

这是我的日志输出CGRect:

 Image crop rect: (0.000000, 53.000000, 320.000000, 322.000000)
Run Code Online (Sandbox Code Playgroud)

这也描述了superview中红色边框视图的框架.

我有什么关键吗?

PS原始图像尺寸(在纵向模式下使用相机拍摄)是:

Original image size: (2448.000000, 3264.000000)
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 7

你可以用CGImageCreateWithImageInRect以下方式裁剪图像

CGImageRef imageRef = CGImageCreateWithImageInRect([uncroppedImage CGImage], bounds);
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
Run Code Online (Sandbox Code Playgroud)


小智 5

不要忘记添加比例参数,否则您将获得低分辨率图像

CGImageRef imageRef = CGImageCreateWithImageInRect([uncroppedImage CGImage], CGRectMake(0, 0, 30, 120));
[imageView setImage:[UIImage imageWithCGImage:imageRef scale:[[UIScreen mainScreen] scale] orientation:UIImageOrientationUp]];
CGImageRelease(imageRef);
Run Code Online (Sandbox Code Playgroud)