Skip to content

Instantly share code, notes, and snippets.

@uruly
Last active July 8, 2019 05:12
Show Gist options
  • Save uruly/e1ff56c0670d425b34dcc1ee5e79784e to your computer and use it in GitHub Desktop.
Save uruly/e1ff56c0670d425b34dcc1ee5e79784e to your computer and use it in GitHub Desktop.
//
// CameraViewController.swift
// CameraTest
//
// Created by Reona Kubo on 2019/07/08.
// Copyright © 2019 Reona Kubo. All rights reserved.
//
import UIKit
import AVFoundation
class CameraViewController: UIViewController {
private var avSession: AVCaptureSession!
private var avDevice: AVCaptureDevice!
private var avInput: AVCaptureInput!
private var avOutput: AVCapturePhotoOutput!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.initCamera()
}
deinit {
avSession.stopRunning()
for output in avSession.outputs {
avSession.removeOutput(output)
}
for input in avSession.inputs {
avSession.removeInput(input)
}
avOutput = nil
avInput = nil
avDevice = nil
avSession = nil
}
private func initCamera() {
// AVキャプチャセッッション
avSession = AVCaptureSession()
if(avSession.canSetSessionPreset(AVCaptureSession.Preset.photo)){
avSession.beginConfiguration()
/* Highのときは9:16で撮影される
Photoのときは 3:4 で撮影される*/
avSession.sessionPreset = AVCaptureSession.Preset.photo
avSession.commitConfiguration()
}
// ここを .front .back で前面・背面カメラを変更
let devicePosition: AVCaptureDevice.Position = .back
// AVキャプチャデバイス
let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera, .builtInTelephotoCamera], mediaType: .video, position: devicePosition)
for device in discoverySession.devices {
if device.position == devicePosition {
avDevice = device
}
}
showCamera()
}
private func showCamera() {
guard let avDevice = avDevice else { return }
do {
avInput = try AVCaptureDeviceInput.init(device:avDevice)
} catch {
print(error)
return
}
// AVキャプチャデバイスインプットをセッションに追加
if(avSession.canAddInput(avInput)){
avSession.addInput(avInput)
avOutput = AVCapturePhotoOutput()
if(avSession.canAddOutput(avOutput)){
avSession.addOutput(avOutput)
}
}
// 画像を表示するレイヤーを生成
let capVideoLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: avSession)
capVideoLayer.videoGravity = .resizeAspectFill
capVideoLayer.frame = view.frame
view.layer.addSublayer(capVideoLayer)
avSession.startRunning()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment