捕获图像并将其设置为UIImageView

时间:2017-02-09 20:21:14

标签: ios camera uiimageview

我正在尝试捕获一个Image并将其设置为UIImageView,因此要创建相机我有以下代码:

class HomeController: BaseController, UIImagePickerControllerDelegate {

var detector: AFDXDetector?
var captureSession : AVCaptureSession?
var stillImageOutput : AVCapturePhotoOutput?
var previewLayer : AVCaptureVideoPreviewLayer?
var camera : AVCaptureDevice!

@IBOutlet weak var cameraBtn: UIButton!
@IBOutlet weak var cameraView: UIView!
@IBOutlet weak var cameraImageView: UIImageView!

    override func viewDidLoad() {
      super.viewDidLoad()
      startCamera()
    }

    func startCamera() {

    do {

        captureSession = AVCaptureSession()
        camera = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .front)
        captureSession?.sessionPreset = AVCaptureSessionPreset1280x720

        let input = try AVCaptureDeviceInput(device: camera)

        if (captureSession?.canAddInput(input))!{
            captureSession?.addInput(input)
            stillImageOutput = AVCapturePhotoOutput()

            if (captureSession?.canAddOutput(stillImageOutput))!{
                print("output added")
                captureSession?.canAddOutput(stillImageOutput)
                previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
                previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
                cameraView.layer.addSublayer(previewLayer!)
                captureSession?.startRunning()
            }
        }

    } catch {

    }
}


@IBAction func cameraBtnPressed(_ sender: Any) {
   if (stillImageOutput?.connection(withMediaType: AVMediaTypeVideo)) != nil
    {
        print("video connection detected")
    }
}
}

出于某种原因,虽然相机正在工作,但仍未调用打印语句“检测到视频连接”

还有其他人知道为什么吗?

1 个答案:

答案 0 :(得分:1)

在captureSession的if语句中?.canAddOutput(stillImageOutput)将captureSession?.canAddOutput(stillImageOutput)更改为.addOutput