我有以下函数来裁剪UIImage的一部分并返回裁剪的UIImage。我传入UIView的框架,它充当用户用来裁剪图像的可移动框。UIView 位于 UIImage 的顶部,当用户按下确认时,我尝试裁剪 UIImage 在 UIView 下方的部分。
private func cropImage(image: UIImage, cropRect: CGRect) -> UIImage {
UIGraphicsBeginImageContextWithOptions(cropRect.size, false, 0)
image.draw(at:CGPoint(x: -cropRect.origin.x, y: -cropRect.origin.y))
let croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return croppedImage!;
}
@IBAction func confirmTapped(_ sender: UIButton) {
let croppedImage = cropImage(image: backgroundImage!, cropRect: mediaView.frame)
}
我正在使用相机框架获取原始UIImage,值得注意的是,我的手机在拍照时处于纵向模式:
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer!)
let dataProvider = CGDataProvider(data: imageData as CFData)
let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)
let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: self.getImageOrientation(forCamera: self.currentCamera))
我遇到的问题是裁剪的 UIImage 结果被放大/放大,并不代表 UIView 下方/框架内的实际区域。
尝试将屏幕比例作为参数传递?
let image = UIImage(cgImage: cgImageRef!, scale: UIScreen.main.scale, orientation: self.getImageOrientation(forCamera: self.currentCamera))
将比例也添加到UIGraphicsBeginImageContext:
UIGraphicsBeginImageContextWithOptions(cropRect.size, false, UIScreen.mainScreen.scale)