如何在iOS中实现自定义相机预览?

时间:2018-07-15 15:58:39

标签: swift4 xcode9

我正在尝试实现自定义相机效果,例如:-Image 我认为这是可以实现的this way 这种功能已在App Store中可用的一个应用程序中实现。这是链接enter link description here 我想复制此应用程序的相机功能。

我已经实现了like this。 我正在使用下面的代码来实现上述功能。 进入ViewController.swift类。

import UIKit
import AVFoundation

 @available(iOS 10.0, *)
class ViewController: UIViewController
{
@IBOutlet weak var vc: UIView!
@IBOutlet weak var img: UIImageView!
override func viewDidLoad() {
    super.viewDidLoad()
    setupCamera()
}
override  func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    session.startRunning()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    session.stopRunning()
}



 @IBOutlet fileprivate var previewView: PreviewView! {
didSet {
  previewView.videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
   previewView.layer.cornerRadius = previewView.layer.frame.size.width/2
    previewView.clipsToBounds = true

   }
  }

  @IBOutlet fileprivate var imageView: UIImageView! {
didSet {
    imageView.layer.cornerRadius = imageView.layer.frame.size.width/2
  imageView.clipsToBounds = true
   }
 }

 fileprivate let session: AVCaptureSession = {
 let session = AVCaptureSession()
  session.sessionPreset = AVCaptureSessionPresetPhoto
  return session
}()

 fileprivate let output = AVCaptureStillImageOutput()

}

   @available(iOS 10.0, *)
extension ViewController {

 func setupCamera() {
let backCamera = AVCaptureDevice.defaultDevice(withMediaType: 
 AVMediaTypeVideo)
guard let input = try? AVCaptureDeviceInput(device: backCamera) else { 
 fatalError("back camera not functional.") }
session.addInput(input)
session.addOutput(output)
previewView.session = session

  }

  }


// MARK: - @IBActions
  @available(iOS 10.0, *)
   private extension ViewController {
    @IBAction func capturePhoto() {

  if let videoConnection = output.connection(withMediaType: AVMediaTypeVideo) {

    output.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (CMSampleBuffer, Error) in
        if let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(CMSampleBuffer) {

            if let cameraImage = UIImage(data: imageData) {
                self.imageView.image = cameraImage

                UIImageWriteToSavedPhotosAlbum(cameraImage, nil, nil, nil)
            }
        }
    })
}

}
 }

还创建“预览类”,并将该类从情节提要文件导入UIView中。 通过以上代码,我实现了this image。 我需要将任何形状的图像图层作为框架添加到UIView中。但是我不知道如何实现这种功能。 因此,基本上,我的任务是如何在UIView中添加任意形状的图像层,以及在捕获图像后如何使用图像层保存图像,例如 Final Image clue image

0 个答案:

没有答案