使用相机拍照并在应用程序中用作 "profile Picture"

Take picture with Camera and use as "profile Picture" within app

我有一个 UIImageView,我想打开相机以便用户可以拍照、裁剪(困难的部分),然后让应用程序将它存储在 class 我已经已经写好了。我以前从未使用过相机,所以我不太确定如何去做。

您需要实施 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,他们会自动将其转换为类似 "Privacy - Camera access" 的内容。然后,您必须在值列中输入说明,说明您需要访问相机的原因。当用户最初被要求允许您的应用访问相机时,将向用户显示此说明。

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

时更改 allowsEditing