将subView添加到相机预览图层

时间:2017-07-16 20:39:14

标签: ios swift avcapturedevice

我想在相机预览图层前面添加一个按钮, 按钮工作正常打印(1234)但我无法看到它。 我将色调颜色更改为白色,但没有任何变化,我仍然没有看到它。 我认为这与添加子图层有关。

class ViewController: UIViewController {
    let captureSession = AVCaptureSession()
    var previewLayer: CALayer?
    var captureDevice: AVCaptureDevice?

    lazy var button: UIButton = {
       let btn = UIButton(type: .system)
        btn.setTitle("Capture", for: .normal)
        btn.tintColor = .white
        btn.translatesAutoresizingMaskIntoConstraints = false
        btn.addTarget(self, action: #selector(hendleFrontCamera), for: .touchUpInside)
        return btn
    }()

    func hendleFrontCamera() {
        print(123)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupButtons()
        preperCamera()
    }

    func setupButtons() {
        self.view.addSubview(button)
        button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
        button.widthAnchor.constraint(equalToConstant: 40).isActive = true
        button.heightAnchor.constraint(equalToConstant: 40).isActive = true
    }

    func preperCamera() {
        captureSession.sessionPreset = AVCaptureSessionPresetiFrame960x540
        if let availableDevice = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .back
            ).devices{
            captureDevice = availableDevice.first
            beginSission()
        }
    }

    func beginSission() {
        guard let captureDeviceInput = try? AVCaptureDeviceInput(device: captureDevice) else { return }
        captureSession.addInput(captureDeviceInput)

        if     let preivewlayer = AVCaptureVideoPreviewLayer(session: self.captureSession) {
            self.previewLayer = preivewlayer
            self.view.layer.insertSublayer(self.previewLayer!, below: self.view.layer)
            captureSession.startRunning()
        }
    }
}

0 个答案:

没有答案