裁剪后 UIImage 旋转 90 度 [英] UIImage getting rotated 90 degrees after cropping

查看:29
本文介绍了裁剪后 UIImage 旋转 90 度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下函数来裁剪 UIImage 的一部分并返回裁剪后的 UIImage.但是,在使用这个裁剪后的 UIImage 时,它​​已经旋转了 90 度.我想你可以这么说,我的图像通常处于纵向模式",我试图在裁剪后保持这种状态.

I have the following function to crop a portion of a UIImage and return the cropped UIImage. However, when using this cropped UIImage, it has been rotated 90 degrees. My image is usually in "portrait mode" I guess you can say, and I'm trying to keep it like that after cropping.

我知道还有其他帖子涉及此问题,但我已尝试实施解决方案,但没有一个对我有用.

I'm aware there are other posts with this problem but I have tried to implement solutions and none have worked for me.

  private func cropImage(image: UIImage, cropRect: CGRect) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(cropRect.size, false, 0);
        let context = UIGraphicsGetCurrentContext();

        context?.translateBy(x: 0.0, y: image.size.height);
        context?.scaleBy(x: 1.0, y: -1.0);
        context?.draw(image.cgImage!, in: CGRect(x:0, y:0, width:image.size.width, height:image.size.height), byTiling: false);
        context?.clip(to: [cropRect]);

        let croppedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return croppedImage!;
    }

由以下创建的原始 UIImage:

Original UIImage created by the following:

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 世界传递到 CGImage 世界让您能够应对各种困难(正如您所发现的);你会丢失缩放和方向信息,图像最终可能会垂直翻转.正常的方式更像是这样:

What you're doing is a very odd way to crop. Passing out of the UIImage world into the CGImage world lets you in for all sorts of difficulties (as you've discovered); you lose scaling and orientation information, and the image can end up flipped vertically. The normal way is more like this:

UIGraphicsBeginImageContextWithOptions(cropRect.size, false, 0)
image.draw(at:CGPoint(x:-cropRect.origin.x, y:-cropRect.origin.y))
let croppedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

另请注意,从 iOS 10 开始,整个 UIGraphicsBeginImageContextWithOptions 舞蹈已经过时,因为您可以使用 UIGraphicsImageRenderer 代替.

Also note that starting in iOS 10 the entire UIGraphicsBeginImageContextWithOptions dance is outmoded, as you can use a UIGraphicsImageRenderer instead.

这篇关于裁剪后 UIImage 旋转 90 度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆