2

UIImagePickerController 是系统提供的用来获取图片和视频的接口。

下面例子来示范使用相机拍照并显示出我们的照片。

先设置ViewController继承UIImagePickerControllerDelegate, UINavigationControllerDelegate。

然后拖入一个ImageView,一个Button到Main.storyboard。分别绑定:

@IBOutlet weak var imageView: UIImageView!
@IBAction func useCamera(sender: AnyObject) {}

然后添加下面代码到useCamera,来使用相机拍照

// 先要判断相机是否可用
if UIImagePickerController.isSourceTypeAvailable(.Camera) {   
    let picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType = UIImagePickerControllerSourceType.Camera
        picker.allowsEditing = true  // 允许拍摄图片后编辑
        self.presentViewController(picker, animated: true, completion: nil)
    } else {
        print("can't find camera")
    }
}

继承UIImagePickerControllerDelegate,为我们实现了拍照后的响应:

imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?)

imagePickerControllerDidCancel(picker: UIImagePickerController)

分别是点击完成后处理照片,点击取消。

这里我们使用后两个:

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
    print("didFinishPickingImage") 
    self.imageView.image = image // 保存拍摄(编辑)后的图片到我们的imageView展示
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) // 将图片保存到相册
    picker.dismissViewControllerAnimated(true, completion: nil) // 退出相机界面
}
 
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    print("imagePickerControllerDidCancel") 
    picker.dismissViewControllerAnimated(true, completion: nil) // 退出相机界面
}

RichardXG
337 声望19 粉丝