【问题标题】:Swift UI camera shows portrait view but image turns out landscapeSwift UI 相机显示纵向视图,但图像变成横向
【发布时间】:2020-07-10 19:12:26
【问题描述】:

我正在尝试让相机预览和照片在 swiftUI 应用程序中工作,我可以显示预览并拍摄照片,但比例出现错误。预览屏幕看起来不错,但一旦发生捕捉,它就会变形并且不会保持纵向。

预览屏幕如下所示:

一些代码:

class CameraController: UIViewController {
    //...
    override func viewDidLoad() {
        //...
        // Setup preview layer
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        previewLayer?.videoGravity = .resizeAspectFill
        previewLayer?.connection?.videoOrientation = .portrait
        previewLayer?.frame = view.frame
        view.layer.insertSublayer(previewLayer!, at: 0)
        //...
    }
}

但在我拍完照片后,我在VStack 中显示的Image 看起来像:

代码是:

VStack {
    Image(uiImage: self.inputImage!)
        .resizable()
        .aspectRatio(contentMode: .fit)
        .edgesIgnoringSafeArea(.all)
}

我使用.fit 是因为我想看到整个事情,但结果完全错了。另外,这是我在viewDidLoad 内部的相机设置代码:

captureSession.beginConfiguration()

// Get device
captureDevice = AVCaptureDevice.default(.builtInDualCamera, for: .video, position: .back)

do {
    // Create input
    let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice!)
    captureSession.addInput(captureDeviceInput)

    // Create output
    photoOutput = AVCapturePhotoOutput()
    captureSession.sessionPreset = .photo
    photoOutput?.setPreparedPhotoSettingsArray(
        [AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg])],
        completionHandler: nil
    )
    captureSession.connections.first?.videoOrientation = .portrait // tested with and and without this line
    captureSession.addOutput(photoOutput!)
    captureSession.commitConfiguration()
} catch {
    print(error)
}

非常感谢任何帮助!

【问题讨论】:

  • 你有解决办法吗?

标签: ios swift camera swiftui


【解决方案1】:

它仅在横向返回,因为使用应用内相机拍摄的图像具有方向。您需要对其进行规范化并显示它。

我对 UIImage 做了一个扩展

func fixOrientation(img:UIImage) -> UIImage {

  if (img.imageOrientation == UIImageOrientation.Up) { 
      return img;
  }

  UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale);
  let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
  img.drawInRect(rect)

  let normalizedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext();
  return normalizedImage;

}

来自这里的原始答案: Normalize Pictures taken by camera

另外,我刚刚对 ImagePickerManager 的复制和粘贴解决方案进行了一些更改:

ImagePickerManager

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多