今天我會介紹如何用swift開發相機且如何使用
class CameraViewController: UIViewController {
var captureSession: AVCaptureSession!
var videoPreviewLayer: AVCaptureVideoPreviewLayer!
override func viewDidLoad() {
super.viewDidLoad()
captureSession = AVCaptureSession()
guard let videoCaptureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else { return }
let videoInput: AVCaptureDeviceInput
do {
videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
} catch {
return
}
if (captureSession.canAddInput(videoInput)) {
captureSession.addInput(videoInput)
} else {
return
}
let videoOutput = AVCaptureVideoDataOutput()
if (captureSession.canAddOutput(videoOutput)) {
captureSession.addOutput(videoOutput)
} else {
return
}
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
videoPreviewLayer.frame = view.layer.bounds
videoPreviewLayer.videoGravity = .resizeAspectFill
view.layer.addSublayer(videoPreviewLayer)
captureSession.startRunning()
}
}
其中在.builtInWideAngleCamera的地方可以選擇你想要的鏡頭
記得在用之前要在info裡加入請求相機權限歐