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

时间:2014-01-09 04:36:43

标签: ios uiimage crop image-resizing cgrect

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

UIViewController with an implementation of 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();

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

这是CGRect

的日志输出
 Image crop rect: (0.000000, 53.000000, 320.000000, 322.000000)

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

我有什么关键吗?

P.S。原始图像尺寸(在纵向模式下使用相机拍摄)为:

Original image size: (2448.000000, 3264.000000)

3 个答案:

答案 0 :(得分:7)

您可以使用CGImageCreateWithImageInRect

裁剪图像
CGImageRef imageRef = CGImageCreateWithImageInRect([uncroppedImage CGImage], bounds);
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);

答案 1 :(得分:5)

不要忘记添加缩放参数,否则会得到低分辨率图像

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

答案 2 :(得分:3)

斯威夫特3:

let imageRef:CGImage = uncroppedImage.cgImage!.cropping(to: bounds)!
let croppedImage:UIImage = UIImage(cgImage: imageRef)
相关问题