AVFoundation作物根据预览宽高比捕获静止图像

我的问题大部分与这个相似:

裁剪由AVCaptureSession捕获的图像

我有一个应用程序使用AVFoundation捕获静止图像。 我的AVCaptureVideoPreviewLayer具有AVLayerVideoGravityResizeAspectFillvideo重力,从而使得向用户显示的预览图片从顶部和底部部分被裁剪。

当用户按下“拍摄”button时,实际拍摄的图像与显示给用户的预览图像不同。 我的问题是如何相应裁剪捕获的图像?

提前致谢。

我用这里提供的UIImage+Resize类别和我写的一些新的方法来完成这个工作。 我重新格式化一些代码,看起来更好,没有testing,但它应该工作。 :))

 - (UIImage*)cropAndResizeAspectFillWithSize:(CGSize)targetSize interpolationQuality:(CGInterpolationQuality)quality { UIImage *outputImage = nil; UIImage *imageForProcessing = self; // crop center square (AspectFill) if (self.size.width != self.size.height) { CGFloat shorterLength = 0; CGPoint origin = CGPointZero; if (self.size.width > self.size.height) { origin.x = (self.size.width - self.size.height)/2; shorterLength = self.size.height; } else { origin.y = (self.size.height - self.size.width)/2; shorterLength = self.size.width; } imageForProcessing = [imageForProcessing normalizedImage]; imageForProcessing = [imageForProcessing croppedImage:CGRectMake(origin.x, origin.y, shorterLength, shorterLength)]; } outputImage = [imageForProcessing resizedImage:targetSize interpolationQuality:quality]; return outputImage; } // fix image orientation, which may wrongly rotate the output. - (UIImage *)normalizedImage { if (self.imageOrientation == UIImageOrientationUp) return self; UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale); [self drawInRect:(CGRect){0, 0, self.size}]; UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return normalizedImage; }