我是靠谱客的博主 细心服饰,最近开发中收集的这篇文章主要介绍iOS_Swift_自定义相机,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1、import所需要的框架

import UIKit

import AVFoundation

2、初始化会话及拍照图层

/// 初始化照相图层

    ///

    /// - Returns: 返回初始化结果

    func initCamera() -> Bool {

 

        // 创建会话

        captureSession = AVCaptureSession()

        captureSession.beginConfiguration()

       

        // 照片图层

        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)

        previewLayer.frame = self.bounds

        previewLayer.videoGravity = AVLayerVideoGravity.resizeAspect

        self.layer.addSublayer(previewLayer)

       

        // 设定输出流

        output = AVCaptureVideoDataOutput()

        if captureSession.canAddOutput(output) {

            captureSession.addOutput(output)

            let queue = DispatchQueue(label: "dispatchQueue_label_1")  // label给queue设定一个标识

            output.setSampleBufferDelegate(self, queue: queue)

            captureSession.commitConfiguration()

            return true

        }

        return false

    }

 

 

3、开始照相

/// 开始照相

    ///

    /// - Parameter position: 前置/后置

    /// - Returns: 成功返回nil 否则返回一个error

    func beginTakePhoto(position: AVCaptureDevice.Position) -> Error? {

        

        self.stopToTakePhoto = false

        

        captureSession.stopRunning()

        

        // 摄像头设备

        let availbleDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: position).devices

        device = availbleDevices.first

        

        do {

            

            for input in captureSession.inputs {

                captureSession.removeInput(input)

            }

            let captureDeviceInput = try AVCaptureDeviceInput(device: device)

            captureSession.addInput(captureDeviceInput)

        } catch {

            return error

        }

        

        captureSession.startRunning()

        

        return nil

    }

    

 

4、停止照相

/// 停止照相

    ///

    /// - Parameter complete: 回调

    func stopTakePhoto (complete:@escaping (UIImage?) -> ())  {

        self.getImgComplete = complete

 // 开始照相之后每刷新一帧都会在代理中回调,使用一个变量来判断是否获取当前帧图片

        self.stopToTakePhoto = true

        self.captureSession.stopRunning()

    }

 

 

5、照相回调,获取照片

 

首先要遵守代理 AVCaptureVideoDataOutputSampleBufferDelegate

// 代理方法

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {

 

        // 根据全局定义的一个变量来判断是否获取照片

        if self.stopToTakePhoto {

 

            DispatchQueue.main.async {

                let image = self.imageConvert(sampleBuffer: sampleBuffer)

                self.getImgComplete!(image) // 用闭包 回传获取的图片

            }

 

        }

    }

 

    // 从CMSampleBuffer中获取图片

    private  func imageConvert(sampleBuffer:CMSampleBuffer?) -> UIImage? {

        guard sampleBuffer != nil && CMSampleBufferIsValid(sampleBuffer!) == true else { return nil }

        let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer!)

        let ciImage = CIImage(cvPixelBuffer: pixelBuffer!)

        return UIImage(ciImage: ciImage)

    }

 

   // 旋转方向

    private  func getCaptureVideoOrientation() -> AVCaptureVideoOrientation {

        switch UIDevice.current.orientation {

        case .portrait,.faceUp,.faceDown:

            return .portrait

        case .portraitUpsideDown: // 如果这里设置成AVCaptureVideoOrientationPortraitUpsideDown,则视频方向和拍摄时的方向是相反的。

            return .portrait

        case .landscapeLeft:

            return .landscapeRight

        case .landscapeRight:

            return .landscapeLeft

        default:

            return .portrait

        }

    }    

 

最后

以上就是细心服饰为你收集整理的iOS_Swift_自定义相机的全部内容,希望文章能够帮你解决iOS_Swift_自定义相机所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(57)

评论列表共有 0 条评论

立即
投稿
返回
顶部