我正在使用此代码在我的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
}
然而,相机显示如下:
它似乎相当于iPhone 4的显示尺寸。
我该如何解决这个问题?我已尝试在viewDidLayoutSubviews
中设置框架,但我无法正确调整尺寸。
答案 0 :(得分:0)
检查是否为所有支持的设备分配了启动映像。如果没有,那么无论你做什么,iOS都会默认为那个大小。
答案 1 :(得分:0)
您不必覆盖layoutSubivews或viewDidLayoutSUbviews方法。
previewView
约束为superview
(如果您使用自动布局)previewLayer
的界限与previewView
bounds
相同。在将帧值赋予边界或绑定值到帧时不要感到困惑。AVLayerVideoGravityResizeAspectFill
。 4.您可以定位previewLayer
并将其置于previewView
的中心位置。使用previewLayer
的位置属性并将其设置为previewView
的中心。
setupSession()
/ viewDidAppear
viewWillAppear
醇>