我有一个UIImageView,我想打开相机,以便用户可以拍照,裁剪它(硬部分),然后让应用程序将它存储在我已编写的类中。我之前从未使用过相机,所以我不太清楚如何做到这一点。
答案 0 :(得分:1)
您需要实施UIImagePickerController
- 这也意味着您需要ViewController
符合UIImagePickerControllerDelegate
和UINavigationControllerDelegate
。首先确保您的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
值