LoginSignup
6
6

More than 5 years have passed since last update.

UIViewにカメラの映像を表示

Last updated at Posted at 2017-03-05

細かい所は全然分かってないけど、とりあえずUIView(ここではcameraViewという名前)にカメラの映像を表示するプログラム

ViewController.swift
import UIKit
import AVFoundation

class ViewController: UIViewController{

    @IBOutlet weak var cameraView: UIView!
    var captureSesssion: AVCaptureSession!
    var stillImageOutput: AVCapturePhotoOutput?
    var previewLayer: AVCaptureVideoPreviewLayer?
    override func viewWillAppear(_ animated: Bool) {

        captureSesssion = AVCaptureSession()
        stillImageOutput = AVCapturePhotoOutput()

        captureSesssion.sessionPreset = AVCaptureSessionPreset1920x1080 // 解像度の設定

        let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

        do {
            let input = try AVCaptureDeviceInput(device: device)

            // 入力
            if (captureSesssion.canAddInput(input)) {
                captureSesssion.addInput(input)

                // 出力
                if (captureSesssion.canAddOutput(stillImageOutput)) {
                    captureSesssion.addOutput(stillImageOutput)
                    captureSesssion.startRunning() // カメラ起動

                    previewLayer = AVCaptureVideoPreviewLayer(session: captureSesssion)
                    previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect // アスペクトフィット
                    previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait // カメラの向き

                    cameraView.layer.addSublayer(previewLayer!)

                    // ビューのサイズの調整
                    previewLayer?.position = CGPoint(x: self.cameraView.frame.width/2, y: self.cameraView.frame.height/2)
                    previewLayer?.bounds = cameraView.frame
                }
            }
        }
        catch {
            print(error)
        }
    }
}


※追記
Info.plistにPrivacy-Camera Usage DescriptionのKeyを追加

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6