Blame view

Twear/Setting/CameraViewController.swift 14.7 KB
75d24c15   yangbin   123
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
  //
  //  CameraViewController.swift
  //  Twear
  //
  //  Created by yangbin on 2021/12/22.
  //
  
  import UIKit
  import AVFoundation
  import Photos
  
  //let rect = CGRect(x: 30, y: 100, width: SCREEN_WIDTH-60, height: SCREEN_HEIGHT-100-100-100)// 底部工具栏 高度100  距离上面 下面都是100
  
  class CameraViewController: UIViewController, BluetoothSyncDelegate {
      
      
      
      
      
      let WIDTH = UIScreen.main.bounds.width
      
      let HEIGHT = UIScreen.main.bounds.height
      // 音视频采集会话
      
      let captureSession = AVCaptureSession()
      
      // 后置摄像头
      @IBOutlet weak var backButton: UIButton!
      
      @IBOutlet weak var toggleButton: UIButton!
      var backFacingCamera: AVCaptureDevice?
      
      // 前置摄像头
      
      var frontFacingCamera: AVCaptureDevice?
      
      // 当前正在使用的设备
      
      var currentDevice: AVCaptureDevice?
      
      // 静止图像输出端
      
      var stillImageOutput: AVCaptureStillImageOutput?
      
      // 相机预览图层
      
      var cameraPreviewLayer:AVCaptureVideoPreviewLayer?
      
      
      //照片拍摄后预览视图
      
      var photoImageview:UIImageView!
      
      
      
      override func viewWillAppear(_ animated: Bool) {
          super.viewWillAppear(animated)
          self.navigationController?.setNavigationBarHidden(true, animated: true)
      }
      
      
      override func viewDidLoad() {
          super.viewDidLoad()
          
          let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
          if authStatus == AVAuthorizationStatus.notDetermined {
              AVCaptureDevice.requestAccess(for: AVMediaType.video) { (granted) in
                  if granted {
                      self.setupUI()
                  } else {
                      self.back(1)
                  }
              }
          } else if authStatus == AVAuthorizationStatus.restricted || authStatus == AVAuthorizationStatus.denied {
              self.cameraAccessAlert()
          } else {
              self.setupUI()
          }
      }
      
      func saveImageToPhotoLibrary() {
          // 判断权限
          switch PHPhotoLibrary.authorizationStatus() {
          case .authorized:
              break
              //                            self.saveImage(image: stillImage)
          case .notDetermined:
              PHPhotoLibrary.requestAuthorization { [weak self] (status) in
                  if status == .authorized {
                      //                                    self?.saveImage(image: stillImage)
                  } else {
                      //                                self?.back(1)
                      print("User denied")
                  }
              }
              
          case .restricted, .denied:
              let alert = UIAlertController(title: LocString("提示"), message: LocString("请在“设置-隐私-照片“选项中,允许'HDF wear'访问你的照片"), preferredStyle: .alert)
              let confirm = UIAlertAction(title: LocString("确定"), style: .default)
              alert.addAction(confirm)
          default:
              break
              
          }
      }
      
      func cameraAccessAlert() {
          let alertVC = UIAlertController(title: LocString("提示"), message: LocString("请在“设置-隐私-相机”选项中,允许'HDF wear'访问你的相机"), preferredStyle: .alert)
          let confirm = UIAlertAction(title: LocString("确定"), style: .destructive) { [weak self] (action) in
              self?.back(1)
          }
          let cancel = UIAlertAction(title: LocString("取消"), style: .default) { [weak self] (action) in
              self?.back(1)
          }
          alertVC.addAction(cancel)
          alertVC.addAction(confirm)
          present(alertVC, animated: true, completion: nil)
      }
      
      func setupUI() {
          createUI()
          view.bringSubviewToFront(backButton)
          view.bringSubviewToFront(toggleButton)
          BluetoothManager.shared.registerSyncDelegate(self)
          BluetoothManager.shared.openCamera(true)
      }
      
      //MARK: - 获取设备,创建自定义视图
      func createUI(){
          // 将音视频采集会话的预设设置为高分辨率照片--选择照片分辨率
          self.captureSession.sessionPreset = AVCaptureSession.Preset.hd1280x720
          
          // 获取设备
          let devices = AVCaptureDevice.devices(for: AVMediaType.video)
          
          for device in devices {
              
              if device.position == AVCaptureDevice.Position.back {
                  
                  self.backFacingCamera = device
                  
              }
              
              else if device.position == AVCaptureDevice.Position.front {
                  
                  self.frontFacingCamera = device
                  
              }
              
          }
          
          //设置当前设备为前置摄像头
          
          self.currentDevice = self.backFacingCamera
          
          do {
              
              // 当前设备输入端
              
              let captureDeviceInput = try AVCaptureDeviceInput(device: currentDevice!)
              
              self.stillImageOutput = AVCaptureStillImageOutput()
              
              // 输出图像格式设置
              
              self.stillImageOutput?.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
              
              self.captureSession.addInput(captureDeviceInput)
              
              self.captureSession.addOutput(self.stillImageOutput!)
              
          }
          
          catch {
              
              //            let alert = UIAlertController(title: "提示", message: "请打开相机权限: 设置-隐私-相机", preferredStyle: .alert)
              //            let confirm = UIAlertAction(title: "确定", style: .default)
              //            alert.addAction(confirm)
              //
              return
              
          }
          
          // 创建预览图层
          
          self.cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
          self.cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
          self.cameraPreviewLayer?.frame = view.layer.bounds
          
          self.view.layer.addSublayer(cameraPreviewLayer!)
          
         
          
          //        Entry point / (_main) undefined. for architecture arm64
          // 启动音视频采集的会话
          
          self.captureSession.startRunning()
          
      }
      
      @objc func pinchCamera(_ recognizer: UIPinchGestureRecognizer) {
          //        if let zoomFactor = currentDevice?.videoZoomFactor {
          //
          //            if zoomFactor < 5.0 {
          
          //                let newZoomFactor = min(zoomFactor + 1.0, 5.0)
          
          do {
              
              try currentDevice?.lockForConfiguration()
              
              currentDevice?.ramp(toVideoZoomFactor: recognizer.scale, withRate: 1.0)
              
              currentDevice?.unlockForConfiguration()
              
              
          }
          
          catch {
              
              print(error)
              
          }
          
          //            }
          
          //        }
      }
      
      
      func didReceiveCameraCommand(status: SetCmd) {
          switch status {
          case .takePicture:
              photoAction()
          case .exitCamera:
              back(1)
          default:
              break
          }
      }
      //照相按钮
      
      @objc func photoAction(){
          
          // 获得音视频采集设备的连接
          
          let videoConnection = stillImageOutput?.connection(with: AVMediaType.video)
          
          // 输出端以异步方式采集静态图像
          
          stillImageOutput?.captureStillImageAsynchronously(from: videoConnection!, completionHandler: { (imageDataSampleBuffer, error) -> Void in
              
              if imageDataSampleBuffer == nil {
                  return
              }
              // 获得采样缓冲区中的数据
              
              let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer!)
              
              // 将数据转换成UIImage
              
              if let stillImage = UIImage(data: imageData!) {
                  
                  
                  //                func saveImageToPhotoLibrary() {
                  // 判断权限
                  switch PHPhotoLibrary.authorizationStatus() {
                  case .authorized:
                      self.saveImage(image: stillImage)
                  case .notDetermined:
                      PHPhotoLibrary.requestAuthorization { [weak self](status) in
                          if status == .authorized {
                              self?.saveImage(image: stillImage)
                          } else {
                              //                                self?.back(1)
                              print("User denied")
                          }
                      }
                      
                  case .restricted, .denied:
                      let alert = UIAlertController(title: LocString("提示"), message: LocString("请在“设置-隐私-照片“选项中,允许'HDF wear'访问你的照片"), preferredStyle: .alert)
                      let confirm = UIAlertAction(title: LocString("确定"), style: .default)
                      alert.addAction(confirm)
                  default:
                      break
                      
                  }
                  //                }
                  
                  
                  //显示当前拍摄照片
                  //                UIImageWriteToSavedPhotosAlbum(stillImage, nil, nil, nil)
                  //                self.photoImageview.isHidden = false
                  //
                  //                self.photoImageview.image = stillImage
                  
              }
              
          })
          
      }
      
      private func saveImage(image: UIImage) {
          PHPhotoLibrary.shared().performChanges({
              PHAssetChangeRequest.creationRequestForAsset(from: image)
          }, completionHandler: { (isSuccess, error) in
              DispatchQueue.main.async {
                  if isSuccess {// 成功
                      //                    MBProgressHUD.showh("已保存到系统相册")
                  }
              }
          })
      }
      
      
      
      @IBAction func toggleCamera(_ sender: Any) {
          captureSession.beginConfiguration()
          
          // 在前置和后置之间切换摄像头
          
          let newDevice = (currentDevice?.position == AVCaptureDevice.Position.back) ? frontFacingCamera : backFacingCamera
          
          // 移除之前所有的输入会话
          
          for input in captureSession.inputs {
              
              captureSession.removeInput(input as! AVCaptureDeviceInput)
              
          }
          
          // 将输入端切换到新的采集设备
          
          let cameraInput: AVCaptureDeviceInput
          
          do {
              
              cameraInput = try AVCaptureDeviceInput(device: newDevice!)
              
          }
          
          catch {
              
              print(error)
              
              return
              
          }
          
          // 添加输入端
          
          if captureSession.canAddInput(cameraInput) {
              
              captureSession.addInput(cameraInput)
              
          }
          
          currentDevice = newDevice
          
          // 提交配置
          
          captureSession.commitConfiguration()
      }
      
      @IBAction func back(_ sender: Any) {
          BluetoothManager.shared.unRegisterSyncDelegate(self)
          BluetoothManager.shared.openCamera(false)
          IsCameraOpen = false
          self.dismiss(animated: true)
          
          //        navigationController?.popViewController(animated: true)
      }
      //取消按钮重拍
      
      @objc func cancelAction(){
          
          //隐藏Imageview
          
          self.photoImageview.isHidden = true
          
      }
      
      //保存按钮-保存到相册
      
      @objc func saveAction(){
          
          //保存照片到相册
          
          UIImageWriteToSavedPhotosAlbum(self.photoImageview.image!, nil, nil, nil)
          
          self.cancelAction()
          
      }
      
  }
  
  extension CameraViewController {
      
      //MARK: - 放大方法
      
      @objc func zoomIn() {
          
          if let zoomFactor = currentDevice?.videoZoomFactor {
              
              if zoomFactor < 5.0 {
                  
                  let newZoomFactor = min(zoomFactor + 1.0, 5.0)
                  
                  do {
                      
                      try currentDevice?.lockForConfiguration()
                      
                      currentDevice?.ramp(toVideoZoomFactor: newZoomFactor, withRate: 1.0)
                      
                      currentDevice?.unlockForConfiguration()
                      
                  }
                  
                  catch {
                      
                      print(error)
                      
                  }
                  
              }
              
          }
          
      }
      
      //MARK: - 缩小方法
      
      @objc func zoomOut() {
          
          if let zoomFactor = currentDevice?.videoZoomFactor {
              
              if zoomFactor > 1.0 {
                  
                  let newZoomFactor = max(zoomFactor - 1.0, 1.0)
                  
                  do {
                      
                      try currentDevice?.lockForConfiguration()
                      
                      currentDevice?.ramp(toVideoZoomFactor: newZoomFactor, withRate: 1.0)
                      
                      currentDevice?.unlockForConfiguration()
                      
                  }
                  
                  catch {
                      
                      print(error)
                      
                  }
                  
              }
              
          }
          
      }
      
      //MARK: - 切换摄像头
      
      @objc func toggleCamera1() {
          
          captureSession.beginConfiguration()
          
          // 在前置和后置之间切换摄像头
          
          let newDevice = (currentDevice?.position == AVCaptureDevice.Position.back) ? frontFacingCamera : backFacingCamera
          
          // 移除之前所有的输入会话
          
          for input in captureSession.inputs {
              
              captureSession.removeInput(input as! AVCaptureDeviceInput)
              
          }
          
          // 将输入端切换到新的采集设备
          
          let cameraInput: AVCaptureDeviceInput
          
          do {
              
              cameraInput = try AVCaptureDeviceInput(device: newDevice!)
              
          }
          
          catch {
              
              print(error)
              
              return
              
          }
          
          // 添加输入端
          
          if captureSession.canAddInput(cameraInput) {
              
              captureSession.addInput(cameraInput)
              
          }
          
          currentDevice = newDevice
          
          // 提交配置
          
          captureSession.commitConfiguration()
          
      }
      
  }