【问题标题】:How do you set previewLayer.connection.videoOrientation in Swift 2?如何在 Swift 2 中设置 previewLayer.connection.videoOrientation?
【发布时间】:2016-02-18 10:00:02
【问题描述】:

在 Objective-C 中你可以这样做:

if ( UIDeviceOrientationIsPortrait( deviceOrientation ) || UIDeviceOrientationIsLandscape( deviceOrientation ) ) {
    AVCaptureVideoPreviewLayer *previewLayer = (AVCaptureVideoPreviewLayer *)self.previewView.layer;
    previewLayer.connection.videoOrientation = (AVCaptureVideoOrientation)deviceOrientation;
}

但是在 Swift 中,翻译最后一行的最佳方式是什么?你不能做“deviceOrientation as AVCaptureVideoOrientation”。

到目前为止我能想到的最好的方法是:

    if(UIDeviceOrientationIsPortrait(deviceOrientation) || UIDeviceOrientationIsLandscape(deviceOrientation)) {
        let myPreviewLayer: AVCaptureVideoPreviewLayer = self.previewLayer
        myPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientation.init(rawValue: deviceOrientation.rawValue-1)!
    }

但这似乎不优雅。 -1 在那里,因为它只是一天结束时的枚举,而 UIDeviceOrientation 枚举在位置 0 有一个“未知”,而 AVCaptureVideoOrientation 没有...

【问题讨论】:

    标签: swift2 ios9 avcapturesession uideviceorientation ios9.1


    【解决方案1】:

    这在 swift 4 上做得很好:

    previewLayer.connection?.videoOrientation = AVCaptureVideoOrientation(rawValue: UIApplication.shared.statusBarOrientation.rawValue)!
    

    【讨论】:

      【解决方案2】:

      试试这个

      let avLayer = (self.previewView.layer as AVCaptureVideoPreviewLayer)
      let connection = avLayer.connection
      let orientation = AVCaptureVideoOrientation(rawValue: self.interfaceOrientation.rawValue)!
      connection.videoOrientation = orientation
      

      【讨论】:

        【解决方案3】:

        这是我得到的转换:

        if UIDeviceOrientationIsPortrait(deviceOrientation) || UIDeviceOrientationIsLandscape(deviceOrientation) {
            var previewLayer: AVCaptureVideoPreviewLayer = previewView.layer
            previewLayer.connection.videoOrientation = deviceOrientation
        }
        

        The converter I used 有时不知道代码应该是什么样子(IntCGFloat),因此如果不进行调试,它可能无法工作。让我知道它是否符合您的要求,例如,变量可能会更改为常量。

        【讨论】:

          【解决方案4】:
          connection.videoOrientation = AVCaptureVideoOrientation.Portrait
          

          您可以在 swift 头文件中找到常量 AVCaptureVideoOrientation 的值。 (斯威夫特 2)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-05-19
            • 1970-01-01
            • 1970-01-01
            • 2023-04-01
            • 1970-01-01
            • 1970-01-01
            • 2020-04-25
            • 1970-01-01
            相关资源
            最近更新 更多