[Swift通天遁地]9、拔劍吧-(9)建立支持縮放、移動、裁切的相機視圖控制器

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-eqfehsgj-kh.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

目錄:[Swift]通天遁地Swiftios

本文將演示建立支持縮放、移動、裁切的相機視圖控制器。git

首先確保已經安裝了所需的第三方類庫。雙擊查看安裝配置文件【Podfile】github

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

根據配置文件中的相關設置,安裝第三方類庫。swift

安裝完成以後,雙擊打開項目文件【DemoApp.xcodeproj】xcode

在左側的項目導航區,打開視圖控制器的代碼文件【ViewController.swift】微信

如今開始編寫代碼,建立一個強大時相機視圖控制器。ide

 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 }

因爲須要使用到相機設備,所以須要在真機設備上進行測試。post

相關文章
相關標籤/搜索