如何使用takePicture()在iOS中以编程方式拍摄照片?

时间:2017-09-13 20:23:08

标签: ios swift uiimagepickercontroller

我正在制作一个应用程序,以帮助视障人士阅读餐厅菜单,所以我需要通过一次双击屏幕来拍摄照片。

我已成功使用UIImagePickerController使用标准捕获界面拍摄照片。为了通过双击实现这一点,我将叠加视图设置为一般的ImageView,禁用了相机控件并调用.takePicture()方法。出于某种原因,处理图像捕获的委托方法不起作用。任何人都可以指出我缺少的东西吗?

我已经评论了当前图像选择器的线条,好像它被称为我永远不会离开它。我的叠加层没有按钮,因为照片拍摄应该通过双击进行。

非常感谢任何帮助。

致以最诚挚的问候,

安德烈。

以下代码:

 import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var debugLabel: UILabel!
    @IBOutlet var tapChangeState: UITapGestureRecognizer!

    @IBOutlet weak var imageView: UIImageView!
    var imagePicker = UIImagePickerController() // instantiates an image picker controller.

    override func viewDidLoad() {
        super.viewDidLoad()
        // setting up Image Picker
        imagePicker.delegate  = self // setup the view controller as the image picker delegate.
        imagePicker.allowsEditing = false // disable image editing by the user
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera // set source as camera
        imagePicker.cameraDevice = UIImagePickerControllerCameraDevice.rear // use rear camera

        // setting up gesture recognizer
        tapChangeState.numberOfTouchesRequired = 1 // number of fingers required for change state detection
        tapChangeState.numberOfTapsRequired = 2

        debugLabel.text = "Loaded"
    }

    @IBAction func tapChangeStateDetected(_ sender: UITapGestureRecognizer) {
        imagePicker.cameraOverlayView = imageView
        imagePicker.showsCameraControls = false // disable camera controls
        imagePicker.takePicture() // takes the shot
        debugLabel.text = "Tap detected."
        //present(imagePicker, animated: true, completion: nil)
    }

    // Conforming to ControllerDelegate protocol:
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            imageView.contentMode = .scaleAspectFill
            imageView.image = selectedImage
            debugLabel.text = "Captured"
        }
        dismiss(animated: true, completion: nil)
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: false, completion: nil)
    }
    // Controller Delegate protocol functions end here
}

1 个答案:

答案 0 :(得分:3)

1。 UIImagePickerController需要先拍照才能拍照。

present(imagePicker, animated: false) {
  self.imagePicker.takePicture()
}

2. 确保在Info.plist中设置了“相机使用权限”。

<key>Privacy - Camera Usage Description</key>
<string>My Awesome App requires access to your phone’s camera.</string>

3。 cameraOverlayView是覆盖在默认相机用户界面上的视图。我相信您的示例中您不想使用imageView,因为这是使用捕获的图像设置的视图。如果您使用cameraOverlayView设置imageView,则会从主视图控制器层次结构中删除imageView。为了让您的示例正常工作,我从IBAction中删除了imagePicker.cameraOverlayView = imageView