用相机拍照并在app中用作“个人资料图片”

时间:2017-02-02 02:06:01

标签: ios swift image camera crop

我有一个UIImageView,我想打开相机,以便用户可以拍照,裁剪它(硬部分),然后让应用程序将它存储在我已编写的类中。我之前从未使用过相机,所以我不太清楚如何做到这一点。

1 个答案:

答案 0 :(得分:1)

您需要实施UIImagePickerController - 这也意味着您需要ViewController符合UIImagePickerControllerDelegateUINavigationControllerDelegate。首先确保您的ViewController执行此操作:

class YourViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

然后你可以创建一个显示相机的方法:

func showCamera() {
    // Check if the device has a camera
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {

        // Device has a camera, now create the image picker controller
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera
        imagePicker.allowsEditing = false

        self.present(imagePicker, animated: true, completion: nil)

    }
    else {
        NSLog("No Camera")
    }
}

然后你必须将此方法作为UIImagePickerControllerDelegate的一部分,它将处理用户用相机拍摄的图像:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    // To dismiss the image picker
    self.dismiss(animated: true, completion: nil)

    let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage

    // Do whatever you wish with the image
}

您还应该注意到Apple现在已经制定了新的隐私协议。如果您想要访问用户的相机或照片库,则需要转到Info.plist并添加NSPhotoLibraryUsageDescription - 否则您的应用会在尝试访问相机时崩溃。转到你的plist并插入一个新行,然后只需粘贴NSPhotoLibraryUsageDescription,他们就会自动将其转换为“隐私 - 相机访问”之类的内容。然后,您必须在值列中输入说明,以了解您需要访问摄像机的原因。当用户最初被要求允许您的应用访问相机时,将向用户显示此说明。

此外,如果您希望用户在拍摄照片后裁剪图片,请在将allowsEditing实例化为UIImagePickerController

时更改true