AVCaptureVideoPreviewLayer看起来是iPhone 4大小

时间:2016-06-07 20:22:04

标签: ios swift autolayout avfoundation avcapturesession

我正在使用此代码在我的iOS 9 Swift应用程序中显示相机:

属性:

@IBOutlet weak var previewView: UIView!

var session: AVCaptureSession!
var input: AVCaptureDeviceInput!
var output: AVCaptureStillImageOutput!
var previewLayer: AVCaptureVideoPreviewLayer?

委托方法:

override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    setupSession()
}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    // Experimental / debugging
    view.layoutSubviews()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    // Experimental / debugging
    previewLayer!.frame = previewView.bounds
}

相机方法:

func setupSession() {
    session = AVCaptureSession()
    session.sessionPreset = AVCaptureSessionPresetPhoto

    let camera = frontCamera()

    do { input = try AVCaptureDeviceInput(device: camera) } catch { return }

    output = AVCaptureStillImageOutput()
    output.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]

    guard session.canAddInput(input) && session.canAddOutput(output) else { return }

    session.addInput(input)
    session.addOutput(output)

    previewLayer = AVCaptureVideoPreviewLayer(session: session)
    previewLayer!.videoGravity = AVLayerVideoGravityResizeAspect
    previewLayer!.frame = previewView.bounds
    previewLayer!.connection?.videoOrientation = .Portrait

    previewView.layer.addSublayer(previewLayer!)

    session.startRunning()
}

func frontCamera() -> AVCaptureDevice! {
    let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
    for device in devices {
        if (device.position == AVCaptureDevicePosition.Front) {
            return device as! AVCaptureDevice
        }
    }
    return nil
}

然而,相机显示如下:

enter image description here

它似乎相当于iPhone 4的显示尺寸。

我该如何解决这个问题?我已尝试在viewDidLayoutSubviews中设置框架,但我无法正确调整尺寸。

2 个答案:

答案 0 :(得分:0)

检查是否为所有支持的设备分配了启动映像。如果没有,那么无论你做什么,iOS都会默认为那个大小。

答案 1 :(得分:0)

您不必覆盖layoutSubivews或viewDidLayoutSUbviews方法。

  1. 确保previewView约束为superview(如果您使用自动布局)
  2. 确保previewLayer的界限与previewView bounds相同。在将帧值赋予边界或绑定值到帧时不要感到困惑。
  3. 将预览图层的视频重力设置为AVLayerVideoGravityResizeAspectFill
  4. 4.您可以定位previewLayer并将其置于previewView的中心位置。使用previewLayer的位置属性并将其设置为previewView的中心。

    1. setupSession() / viewDidAppear
    2. 中拨打viewWillAppear