你如何在Swift 2中设置previewLayer.connection.videoOrientation?

时间:2015-11-17 05:51:35

标签: swift2 ios9 avcapturesession uideviceorientation ios9.1

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

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

但是在Swift中,翻译最后一行的最佳方法是什么?您不能将&device 34设备定义为AVCaptureVideoOrientation"。

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

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

但这似乎不够优雅。 -1是因为它只是一天结束时的枚举,并且UIDeviceOrientation枚举有一个"未知"位于0的AVCaptureVideoOrientation没有...

4 个答案:

答案 0 :(得分:1)

这在 swift 4

上做得很好
previewLayer.connection?.videoOrientation = AVCaptureVideoOrientation(rawValue: UIApplication.shared.statusBarOrientation.rawValue)!

答案 1 :(得分:0)

试试这个

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

答案 2 :(得分:0)

这是我得到的转换:

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

The converter I used往往不知道代码应该看起来像什么时候(IntCGFloat),所以如果不进行调试,它可能无法正常工作。让我知道它是否符合您的要求,例如,变量可能会更改为常量。

答案 3 :(得分:0)

connection.videoOrientation = AVCaptureVideoOrientation.Portrait

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