iOS 自定义简单相机

2020-11-01  本文已影响0人  移动的键盘

import UIKit

@objc public class YXCamera: UIView ,AVCapturePhotoCaptureDelegate {

    private lazy var session: AVCaptureSession = {

        letsession =AVCaptureSession.init()

        session.sessionPreset= .high

        return session

    }()

    private lazy var capLayer:AVCaptureVideoPreviewLayer = {

        letlayer =AVCaptureVideoPreviewLayer.init(session:self.session)

        layer.frame=self.bounds

       layer.videoGravity = .resizeAspectFill

        return layer

    }()

   private lazy var capInput:AVCaptureDeviceInput? = {

        if let device =AVCaptureDevice.default( .builtInWideAngleCamera, for: .video, position: .front) {

            var input:AVCaptureDeviceInput?

           do{

                try input =AVCaptureDeviceInput.init(device: device)

            }catch{

                print(error)

            }

            return input

        }

        returnnil

    }()

    private lazy var capOutput:AVCapturePhotoOutput = {

        let output = AVCapturePhotoOutput.init()

        return output

    }()

    override init(frame:CGRect) {

        super.init(frame: frame)

        if self.deviceStatus() != .authorized {

            print("未授权")

            return

        }

        if self.capInput == nil {

            print("捕捉设备输入异常")

            return

        }

        self.layer.addSublayer(self.capLayer)

        if self.session.canAddInput(self.capInput!) {

            self.session.addInput(self.capInput!)

        }

        if self.session.canAddOutput(self.capOutput) {

            self.session.addOutput(self.capOutput)

        }

        self.session.startRunning()

    }

    public func deviceStatus() -> AVAuthorizationStatus {

        let status =AVCaptureDevice.authorizationStatus(for: .video)

        return status

    }

    public func start() {

        let setting = AVCapturePhotoSettings.init(format: [AVVideoCodecKey:AVVideoCodecType.jpeg])

        self.capOutput.capturePhoto(with: setting, delegate:self)

    }

    publicfuncphotoOutput(_output:AVCapturePhotoOutput, didFinishProcessingPhoto photo:AVCapturePhoto, error:Error?) {

       if let data = photo.fileDataRepresentation() {

            if let image =UIImage.init(data: data) {

             UIImageWriteToSavedPhotosAlbum(image,self,#selector(saveImage(image:didFinishSavingWithError:contextInfo:)),nil)

            }

        }

    self.session.stopRunning()

    }

    @objc private func saveImage(image:UIImage, didFinishSavingWithError error:NSError?, contextInfo:AnyObject) {

        if error!=nil {

            print("保存失败",error!)

        } else{

            print("保存成功")

        }

    }

    required init?(coder:NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }

}

上一篇下一篇

猜你喜欢

热点阅读