iOS:自定义相机如何始终以正确的方向保存图像?

Zij*_*ost 5 iphone ios

我目前正在使用 IOS 实现自定义相机。我希望相机始终以正确的方向将图像保存到相册,就像官方 iOS 相机一样:无论您以什么方向握住相机,您始终可以看到保存正确方向的照片。我检查了许多源代码,它们似乎使用以下方式随意保存图像:

var image  = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.right)
Run Code Online (Sandbox Code Playgroud)

但这仅在设备直立时有效 谁能提供任何建议?

我也试图获得方向

let uiorientation = UIApplication.shared.statusBarOrientation
Run Code Online (Sandbox Code Playgroud)

但是当屏幕被纵向锁定时,它总是返回纵向。

Abh*_*yal 3

当你获取对象时,你必须更新图像旋转UIImage。将从图像选择器获取的图像传递给此方法

迅速

func getNormalizedImage(rawImage: UIImage) -> UIImage {

    if (rawImage.imageOrientation == .up) {
        return rawImage
    }

    UIGraphicsBeginImageContextWithOptions(rawImage.size, false, rawImage.scale)
    rawImage.draw(in: CGRect(x:0, y:0, width:rawImage.size.width, height:rawImage.size.height))

    let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return normalizedImage!
}
Run Code Online (Sandbox Code Playgroud)

Objective-C

+(UIImage *)getNormalizedImage:(UIImage *)rawImage {

    if(rawImage.imageOrientation == UIImageOrientationUp)
    return rawImage;

    UIGraphicsBeginImageContextWithOptions(rawImage.size, NO, rawImage.scale);
    [rawImage drawInRect:(CGRect){0, 0, rawImage.size}];
    UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return normalizedImage;
}
Run Code Online (Sandbox Code Playgroud)