0

我正在尝试在点击 UIView 时捕获静止图像。

项目来自: https ://github.com/googlesamples/ios-vision

FaceDetectorDemo → FaceDetector → CameraViewController.m

我将人脸检测器项目从 Objective-C 转换为 Swift,但我需要添加一个额外的功能,用户点击屏幕进行捕捉,但无法弄清楚。

我的代码:

@IBOutlet weak var placeholder: UIView! 
var stillImageOutput = AVCaptureStillImageOutput()

for face in faces
{
  //somewhere in here called faceDetected() method
}

func faceDetected() -> Void
{
    let tapped = UITapGestureRecognizer(target:self,action:#selector(saveToCamera))      
    placeholder.addGestureRecognizer(tapped)
    placeholder.isUserInteractionEnabled = true
}

@objc func saveToCamera(_ sender: UIGestureRecognizer)
{
    if let videoConnection = stillImageOutput.connection(with: AVMediaType.video) {
        stillImageOutput.captureStillImageAsynchronously(from: videoConnection) {
            (imageDataSampleBuffer, error) -> Void in
            let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer!)
            UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData!)!, nil, nil, nil)
        }
    }
}

saveToCamera点击UIView.

4

1 回答 1

2
  • 没有被调用,saveToCamera因为当你添加了 placeholder.addGestureRecognizer(tap)而不是 placeholder.addGestureRecognizer(tapped),不是tap但是tapped
  • 在选择器中,方法必须是:saveToCamera(_:)

这是完整的代码。有用。

  func faceDetected() {
        let tapped = UITapGestureRecognizer(target:self,action:#selector(self.saveToCamera(_:)))
        placeholder.addGestureRecognizer(tapped)
        placeholder.isUserInteractionEnabled = true
    }



    @objc func saveToCamera(_ sender: UIGestureRecognizer) {

        if let videoConnection = stillImageOutput.connection(with: AVMediaType.video) {
            stillImageOutput.captureStillImageAsynchronously(from: videoConnection) {
                (imageDataSampleBuffer, error) -> Void in
                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer!)
                UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData!)!, nil, nil, nil)
            }
        }
    }
于 2019-02-11T08:42:27.873 回答