【发布时间】:2017-07-30 22:24:35
【问题描述】:
我正在使用 AVFoundation 摄像头制作 iPhone 应用,但摄像头无法正确缩放。
我认为我已经做了很多工作以使其大小相同,我将视频重力更改为 ResizeAspectFill 并将 previewlayer.frame.size 更改为 self.layer.frame.size。
为什么我的预览层没有覆盖整个视图?是我打错了还是忘记了我需要输入?谢谢!
代码:
import AVFoundation
import UIKit
import QuartzCore
class View1: UIViewController {
let captureSession = AVCaptureSession()
var previewLayer: CALayer!
var captureDevice: AVCaptureDevice!
@IBOutlet weak var photoButton: UIButton!
@IBOutlet weak var cameraView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
photoButton.layer.zPosition = 1
}
@IBAction func photoButtonpressed(_ sender: UIButton) {
let button = sender as UIButton
if (button.tag == 1){
print("Photobutton clicked")
}
}
func prepareCamera(){
captureSession.sessionPreset = AVCaptureSessionPreset1920x1080
if let availableDevices = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera],
mediaType: AVMediaTypeVideo,
position: .back).devices {
captureDevice = availableDevices.first
beginSession()
}
}
func beginSession(){
do {
let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
captureSession.addInput(captureDeviceInput)
} catch {
print(error.localizedDescription)
}
if let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession){
self.previewLayer = previewLayer
self.view.layer.addSublayer(self.previewLayer)
self.previewLayer.frame = self.view.layer.frame
self.previewLayer.bounds = self.view.bounds
self.previewLayer.contentsGravity = AVLayerVideoGravityResizeAspectFill
captureSession.startRunning()
let dataOutput = AVCaptureVideoDataOutput()
dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString): NSNumber(value: kCVPixelFormatType_32BGRA)]
dataOutput.alwaysDiscardsLateVideoFrames = true
if captureSession.canAddOutput(dataOutput) {
captureSession.addOutput(dataOutput)
captureSession.commitConfiguration()
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
prepareCamera()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
【问题讨论】:
-
您需要覆盖
viewDidLayoutSubviews并执行:self.previewLayer.frame = self.view.bounds,因为图层不受约束。他们采用父级的边界,但是当父级布局时它不会调整大小..所以你必须像这样手动完成。self.previewLayer.frame = self.view.layer.frame self.previewLayer.bounds = self.view.bounds是错误的。设置框架后不要更改边界。仅设置框架就足够了,因为框架实际上是“位置”加上“边界”。 -
这就是视图控制器中的所有代码吗?你在
viewDidLoad之前拥有的这个cameraView出口是什么,但从不在你的代码中使用?它来自故事板,我想……有限制吗?
标签: ios iphone swift avfoundation