1 class ViewController:UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate { 2 var imageView:UIImageView! 3 var imagePickerController:UIImagePickerController! 4 override func viewDidLoad() { 5 super.viewDidLoad() 6 // Do any additional setup after loading the view, typically from a nib. 7 8 self.imageView = UIImageView(frame:CGRect(x:20, y:120, width:280, height:200)) 9 self.view.addSubview(imageView) 10 11 let button = UIButton(frame:CGRect(x:20, y:60, width:280, height:40)) 12 button.setTitle(“选择一张图片”, for:UIControlState()) 13 button.addTarget(self, action:
UIControlEvents.touchUpInside) 14 button.backgroundColor = UIColor.darkGray 15 self.view.addSubview(button) 16 } 17 func pickImage(){ 18 self.imagePickerController = UIImagePickerController() 19 self.imagePickerController.delegate = self 20 self.imagePickerController.allowsEditing = true 21 self.imagePickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary 22 23 self.imagePickerController.navigationBar.barTintColor = UIColor.orange 24 self.imagePickerController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] 25 self.imagePickerController.navigationBar.tintColor = UIColor.white 26 27 self.present(self.imagePickerController, animated: true, completion:nil) 28 } 29 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String:AnyObject]) { 30 print(info[“UIImagePickerControllerMediaType”]) 31 print(info[“UIImagePickerControllerCropRect”]) 32 print(info[“UIImagePickerControllerReferenceURL”]) 33 self.imageView.image = info[“UIImagePickerControllerEditedImage”] as?UIImage 34 self.dismiss(animated:true, completion:nil) 35 } 36 func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { 37 self.dismiss(animated:true, completion:nil) 38 }
//将上面的查询相册,改成调用相机 17 func pickImage() 18 { 19 if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.20 { 21 self.imagePickerController = UIImagePickerController() 22 self.imagePickerController.sourceType = UIImagePickerControllerSourceType.camera 23 self.imagePickerController.cameraDevice = UIImagePickerControllerCameraDevice.rear 24 self.imagePickerController.showsCameraControls = true 25 self.imagePickerController.delegate = self 26 self.imagePickerController.allowsEditing = true 27 self.imagePickerController.navigationBar.barTintColor = UIColor.orange 28 self.imagePickerController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white] 29 self.imagePickerController.navigationBar.tintColor = UIColor.white 30 self.present(self.imagePickerController, animated: true, completion:nil) 31 } 32 }
//UIImagePickerControllerSourceType的枚举类型
image.png
// didFinishPickingMediaWithInfo参数的键值对
image.png