使用 Swift 从 iOS 相机拍摄照片
iosiphone/ipadmobile developmentswift更新于 2026/1/17 11:52:17
为了在 Swift 中从相机拍摄照片,我们可以使用 AVFoundation,它是 iOS SDK 中的一个框架,但我们应该尽量避免使用它,除非我们的相机应用需要大量自定义功能。在本例中,我们只从相机拍摄一张照片并将其显示在视图上。在本例中,我们将使用图像选择器而不是 AVFoundation。
首先,创建一个项目,并在 Storyboard 中的视图控制器上添加一个图像视图。在其类中创建输出口。现在在 ViewController 类中将其与 − 协议一致。
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate
之后创建一个 objc 函数。
@objc func openCamera(){
}
现在在 View 加载完毕后,向视图控制器添加一个点击手势识别器,当屏幕被点击时,该识别器会调用 openCamera 函数。
override func viewDidLoad() {
super.viewDidLoad()
let gesture = UITapGestureRecognizer(target: self, action: #selector(openCamera))
self.view.addGestureRecognizer(gesture)
}
现在在函数中添加以下代码行。
@objc func openCamera() {
let imgPicker = UIImagePickerController()
imgPicker.delegate = self
imgPicker.sourceType = .camera
imgPicker.allowsEditing = false
imgPicker.showsCameraControls = true
self.present(imgPicker, animated: true, completion: nil)
}
完成上述步骤后,我们将实现 UIImagePickerControllerDelegate 的 didFinishPickingMediaWithInfo 方法,并在该方法中获取用户从相机捕获的图像。
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey :
Any]) {
if let img = info[UIImagePickerController.InfoKey.editedImage] as?
UIImage {
self.imgV.image = img
self.dismiss(animated: true, completion: nil)
}
else {
print(&"error&")
}
}
}
现在,我们需要在 info.plist 中添加相机使用描述键,并描述我们的应用为何要使用相机。当我们在 iPhone 上运行此代码并拍摄图像时,就会生成以下结果。另请注意,此应用无法在模拟器上运行。
