[Swift通天遁地]九、拔剑吧-(9)创建支持缩放、移动、裁切的相机视图控制器

本文将演示创建支持缩放、移动、裁切的相机视图控制器。

首先确保已经安装了所需的第三方类库。双击查看安装配置文件【Podfile】

1 platform :ios, '12.0'
2 use_frameworks!
3 
4 target 'DemoApp' do
5     source 'https://github.com/CocoaPods/Specs.git'
6     pod "ALCameraViewController"
7 end

根据配置文件中的相关设置,安装第三方类库。

安装完成之后,双击打开项目文件【DemoApp.xcodeproj】

在左侧的项目导航区,打开视图控制器的代码文件【ViewController.swift】

现在开始编写代码,创建一个强大时相机视图控制器。

 1 import UIKit
 2 //引入已经安装的第三方类库
 3 import ALCameraViewController
 4 
 5 class ViewController: UIViewController {
 6     
 7     override func viewDidLoad() {
 8         super.viewDidLoad()
 9         // Do any additional setup after loading the view, typically from a nib.
10         
11         //添加一个按钮,当用户点击该按钮时,弹出相机视图控制器。
12         let button = UIButton(type: .roundedRect)
13         //设置按钮的显示区域
14         button.frame = CGRect(x: 80, y: 180, width: 150, height: 44)
15         //设置按钮的背景颜色为橙色
16         button.backgroundColor = UIColor.orange
17         //设置按钮的前景颜色为白色
18         button.tintColor = UIColor.white
19         //设置按钮在正常状态下的标题文字
20         button.setTitle("Show camera", for: .normal)
21         //给按钮绑定点击事件
22         button.addTarget(self, action: #selector(ViewController.showCamera(_:)), for: .touchUpInside)
23         
24         //设置根视图的背景颜色为橙色
25         self.view.backgroundColor = UIColor.orange
26         //将按钮控件添加到根视图
27         self.view.addSubview(button)
28     }
29     
30     //添加一个方法,用来响应按钮的点击事件
31     @objc func showCamera(_ button:UIButton)
32     {
33         //设置在相机视图中运行进行裁切。
34         let croppingParameters = CroppingParameters()
35         //初始化一个相机视图控制器,
36         //并在一个代码块中,处理由相机视图控制器返回的图片内容。
37         let cameraViewController = CameraViewController(croppingParameters: croppingParameters) { [weak self] image, asset in
38             //初始化一个指定显示区域的视图对象。
39             let imageView = UIImageView(frame: CGRect(x: 40, y: 40, width: 240, height: 240))
40             //使用图像视图对象,显示返回的图片。
41             imageView.image = image
42             //将图像视图添加到根视图。
43             self?.view.addSubview(imageView)
44             //关闭打开的视图控制器
45             self?.dismiss(animated: true, completion: nil)
46         }
47         
48         present(cameraViewController, animated: true, completion: nil)
49     }
50     
51     override func didReceiveMemoryWarning() {
52         super.didReceiveMemoryWarning()
53         // Dispose of any resources that can be recreated.
54     }
55 }

由于需要使用到相机设备,因此需要在真机设备上进行测试。

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10357343.html