本文将演示从系统相册中读取图片。
在项目导航区,打开视图控制器的代码文件【ViewController.swift】
1 import UIKit 2 3 //添加两个协议:UIImagePickerControllerDelegate, UINavigationControllerDelegate 4 //来实现加载和读取相册的功能 5 class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { 6 7 //添加一个图像视图属性,用来显示从相册中读取的照片 8 var imageView: UIImageView! 9 //添加一个图片拾取控制器,作为当前视图控制器的属性 10 var imagePickerController: UIImagePickerController! 11 12 override func viewDidLoad() { 13 super.viewDidLoad() 14 // Do any additional setup after loading the view, typically from a nib. 15 16 //初始化图像视图,并设置其位置在(20,120),尺寸为(280,200)。 17 self.imageView = UIImageView(frame: CGRect(x: 20, y: 120, 280, height: 200)) 18 //然后将图像视图,添加到当前视图控制器的根视图。 19 self.view.addSubview(imageView) 20 21 //创建一个按钮控件,并设置其位置在(20,60),尺寸为(280,40) 22 let button = UIButton(frame: CGRect(x: 20, y: 60, 280, height: 40)) 23 //同时设置按钮在正常状态下的标题文字。 24 button.setTitle("选择一张图片", for: .normal) 25 //然后给按钮绑定点击事件 26 button.addTarget(self, action: #selector(ViewController.pickImage), for: UIControl.Event.touchUpInside) 27 //设置按钮的背景颜色为深灰色 28 button.backgroundColor = UIColor.darkGray 29 30 //同样将按钮,添加到当前视图控制器的根视图 31 self.view.addSubview(button) 32 } 33 34 //添加一个方法,用来响应按钮的点击事件 35 @objc func pickImage() 36 { 37 //初始化图片拾取控制器对象 38 self.imagePickerController = UIImagePickerController() 39 //设置图片拾取控制器的代理对象,为当前的视图控制器 40 self.imagePickerController.delegate = self 41 //设置图片拾取控制器,是否允许用户移动、缩放和剪切图片 42 self.imagePickerController.allowsEditing = false 43 //设置图片拾取控制器的来源类型为系统相册 44 self.imagePickerController.sourceType = UIImagePickerController.SourceType.photoLibrary 45 //设置图片拾取控制器导航条的前景色为橙色 46 self.imagePickerController.navigationBar.barTintColor = UIColor.orange 47 //设置图片拾取控制器的着色颜色为白色 48 self.imagePickerController.navigationBar.tintColor = UIColor.white 49 //最后在当前视图控制器窗口,展示图片拾取控制器。 50 self.present(self.imagePickerController, animated: true, completion: nil) 51 } 52 53 //添加一个代理方法,用来响应完成图片拾取的事件 54 func imagePickerController(_ picker: UIImagePickerController, 55 didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { 56 57 //在控制台打印输出获得的数据媒体类型 58 print(info[UIImagePickerController.InfoKey.mediaType] ?? "") 59 //在控制台打印输出获得的参考路径 60 print(info[UIImagePickerController.InfoKey.referenceURL] ?? "") 61 //将用户选择的图片,赋予图像视图 62 self.imageView.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage 63 //然后取消图片拾取控制器的展示 64 self.dismiss(animated: true, completion: nil) 65 } 66 67 //添加一个代理方法,用来响应用户取消图片拾取的事件 68 func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { 69 //当用户取消图片拾取时,隐藏图片拾取控制器 70 self.dismiss(animated: true, completion: nil) 71 } 72 73 override func didReceiveMemoryWarning() { 74 super.didReceiveMemoryWarning() 75 // Dispose of any resources that can be recreated. 76 } 77 }