多媒体应用-swift
照片选择主要是通过UIImagePickerController控制器实例化一个对象,然后通过self.PresentViewController方法推出界面显示。需要实现代理UIImagePickerControllerDelegate,UINavigationControllerDelegate。
通过isSourceTypeAvailable方法判断设置是否支持照相机、图片库、相册功能。
使用相册功能主要以下一个步骤:
1)判断是否支持要使用的图片库或相机功能;
2)初始化图片控制器对象;
3)指定图片控制器对象的代理;
4)指定图片控制器类型;
5)弹出显示图片控制器;
6)实现图片控制器代理方法。
// MARK: - 选择照片 /*----- 选择照片 ------*/ @IBAction func addImageButtonClick() { let actionSheet = UIActionSheet(title: "请选择", delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "从相册选","拍照") actionSheet.showInView(self.view) }
// MARK: - UIActionSheetDelegate func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { if buttonIndex != actionSheet.cancelButtonIndex { if buttonIndex == 1 //从相册选 { self.fromAlbum() }else if buttonIndex == 2 //拍照 { self.fromPhotograph() } } }
// MARK: - 选取相册 func fromAlbum() { //判断设置是否支持图片库 if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) { //初始化图片控制器 let picker = UIImagePickerController() //设置代理 picker.delegate = self //设置媒体类型 picker.mediaTypes = [kUTTypeImage as String,kUTTypeVideo as String] //设置允许编辑 picker.allowsEditing = true //指定图片控制器类型 picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary //弹出控制器,显示界面 self.presentViewController(picker, animated: true, completion: { () -> Void in }) } else { let aler = UIAlertView(title: "读取相册错误!", message: nil, delegate: nil, cancelButtonTitle: "确定") aler.show() } }
// MARK: - 拍照 func fromPhotograph() { if UIImagePickerController.isSourceTypeAvailable(.Camera) { //创建图片控制器 let picker = UIImagePickerController() //设置代理 picker.delegate = self //设置来源 picker.sourceType = UIImagePickerControllerSourceType.Camera //设置镜头 if UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Front) { picker.cameraDevice = UIImagePickerControllerCameraDevice.Front } //设置闪光灯 picker.cameraFlashMode = UIImagePickerControllerCameraFlashMode.On //允许编辑 picker.allowsEditing = true; //打开相机 self.presentViewController(picker, animated: true, completion: { () -> Void in }) } else { let aler = UIAlertView(title: "找不到相机!", message: nil, delegate: nil, cancelButtonTitle: "确定") aler.show() } }
// MARK: - UIImagePickerControllerDelegate //选择图片成功之后代理 func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { //查看info对象 print(info) //获取选择的原图 let image = info[UIImagePickerControllerOriginalImage] as! UIImage //赋值,图片视图显示图片 picView.image = image //图片控制器退出 picker.dismissViewControllerAnimated(true, completion: { () -> Void in }) } //取消图片控制器代理 func imagePickerControllerDidCancel(picker: UIImagePickerController) { //图片控制器退出 picker.dismissViewControllerAnimated(true, completion: { () -> Void in }) }
可以通过引入MobileCoreServices.framework,来设置mediaTypes属性设置媒体的类型。