使用UIView框架裁剪UIImage

时间:2018-03-15 22:11:33

标签: ios swift uiimage

我有以下函数来裁剪UIImage的一部分并返回裁剪的UIImage。我传入一个UIView的框架,它作为一个可移动的框,供用户裁剪图像。 UIView位于UIImage的顶部,当用户按下确认时,我尝试在UIView下面裁剪UIImage的部分。

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框架下方/内部的实际区域。

1 个答案:

答案 0 :(得分:0)

尝试将屏幕比例作为参数传递?

let image = UIImage(cgImage: cgImageRef!, scale: UIScreen.main.scale, orientation: self.getImageOrientation(forCamera: self.currentCamera))

将比例添加到UIGraphicsBeginImageContext:

 UIGraphicsBeginImageContextWithOptions(cropRect.size, false, UIScreen.mainScreen.scale)