前提・実現したいこと
小窓のようなカメラ映像を表示しようと試みていますが,なんの表示も出ません。
ただ,同じ表示をストーリーボードで実現させようとすると表示されます。
また,コードだけでもViewControllerのviewにはカメラ映像を表示させることができます。
できるだけコードだけで書きたいです。
AVPreviewLayerの問題なのかと予想していますが,表示できるviewとできないviewの違いが分かりません。
どなたか教えて頂きたいです。
よろしお願いします。
該当のソースコード
import UIKit import AVFoundation class ViewController: UIViewController { var captureSession: AVCaptureSession! var stillImageOutput: AVCapturePhotoOutput! var previewLayer: AVCaptureVideoPreviewLayer! var cameraView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view }() let backgroundView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .gray return view }() override func viewDidLoad() { super.viewDidLoad() setupViews() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) captureSession = AVCaptureSession() stillImageOutput = AVCapturePhotoOutput() captureSession.sessionPreset = .photo let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .back) if let device = discoverySession.devices.first{ do { let input = try AVCaptureDeviceInput(device: device) // 入力 if (captureSession.canAddInput(input)) { captureSession.addInput(input) // 出力 if (captureSession.canAddOutput(stillImageOutput)) { captureSession.addOutput(stillImageOutput) captureSession.startRunning() previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspect 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) } } } func setupViews(){ cameraView = UIView() cameraView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(backgroundView) self.view.addSubview(cameraView) backgroundView.frame = self.view.frame self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[v(100)]-4-|", options: .alignAllTop, metrics: nil, views: ["v": cameraView])) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-8-[v(100)]", options: .alignAllLeft, metrics: nil, views: ["v": cameraView])) } }
試したこと
backgroundColorなどを変更して試したところviewの存在は確認できました。
weak 宣言で書こうとしましたが,うまくいきませんでした。
補足情報(FW/ツールのバージョンなど)
xcode 10.1
macOS10.14.2
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/24 02:09