微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何修复 AVCapturevideopreviewlayer 小于实际相机视图

如何解决如何修复 AVCapturevideopreviewlayer 小于实际相机视图

我正在开发一个应用程序,该应用程序会定期拍照作为研究工作的一部分,但我是 OOP 的新手并且很快,并且对可能导致此问题的原因有些困惑。我认为这是因为 UIView 的尺寸小于相机视图尺寸,并且在显示时被剪掉了,我不确定如何对其进行编程以适应 UIView 的尺寸。这是我的代码
Video Preview Captured image

import UIKit
import AVFoundation

class SecondViewController: UIViewController {
    
    //Creates session between camera input and data output
    let session = AVCaptureSession()
    var camera : AVCaptureDevice?
    var cameraPreviewLayer : AVCaptureVideoPreviewLayer?
    var cameraCaptureOutput : AVCapturePhotoOutput?
    
    //Connects between this code document and Story Board
    @IBOutlet weak var Time: UITextField!
    @IBOutlet weak var Start: UIButton!
    @IBOutlet weak var Cameraview: UIView!


   //Misc Variables
    var alert: UIAlertController!
    var sPhoto : UIImage?
    var completionHandler : ((UIImage?) -> Void)?
    var timerCount:Bool  = false
    var timer:Timer = Timer()
    
    override func viewDidLoad() {
        initializeCaptureSession()
        super.viewDidLoad()
        //assigns delegates to self
        Time.delegate = self
    }
    //Brings down Time keypad when any area other than keypad is touched
    override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?) {
        Time.resignFirstResponder()
    }
    
    func initializeCaptureSession(){
        //Set's sessions presets
        session.sessionPreset = AVCaptureSession.Preset.photo
        //Initalize Camera
        camera = AVCaptureDevice.default(for: AVMediaType.video)
        
        do{
            if(camera == nil){
                print("No Camera Detected")
            }
            else{
            let cameraCaptureInput = try AVCaptureDeviceInput(device: camera!)
            //Set's Camera Output
            cameraCaptureOutput = AVCapturePhotoOutput()
            session.addInput(cameraCaptureInput)
            session.addOutput(cameraCaptureOutput!)
            }
        } catch{
            print(error.localizedDescription)
        }
        cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
        let rootLayer: CALayer = self.Cameraview.layer
        rootLayer.masksToBounds=false
        cameraPreviewLayer?.frame = rootLayer.bounds
        rootLayer.addSublayer(self.cameraPreviewLayer!)
        cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
        session.startRunning()
    }
    //Function that creates alert that dismisses
    func notifyUser(message: String) -> Void
    {
        let alert = UIAlertController(title: "",message: message,preferredStyle: UIAlertController.Style.alert)
          present(alert,animated: true,completion: nil)
        dispatchQueue.main.asyncAfter(deadline: .Now() + 1) { [uNowned self] in
           self.dismiss(animated: true)
          }
    }
    
    @IBAction func Startpressed(_ sender: Any) {
        if(Time.text!.isEmpty == true){
            notifyUser(message: "Please enter a interval")
        }
        else{
            if(timerCount){
                  timerCount = false
                  Start.setTitle("Start",for: .normal)
                  Start.backgroundColor = UIColor.green
                  timer.invalidate()
              }
            else{
                timerCount = true
                Start.setTitle("Stop",for: .normal)
                Start.backgroundColor = UIColor.red
                timer = Timer.scheduledTimer(withTimeInterval: Double(Time.text!)!,repeats: true) { [weak self] timer in
                      self?.takePicture()
                }
            }
        }
    }
    func takePicture() {
        notifyUser(message: "Image Captured")
        //This is where you declare settings for the camera
        let settings = AVCapturePhotoSettings()
        settings.flashMode = .auto
        //Actually takes the photo
        cameraCaptureOutput?.capturePhoto(with: settings,delegate: self)
    }
}

//Extensions
extension SecondViewController : UITextFieldDelegate{
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

extension SecondViewController : AVCapturePhotoCaptureDelegate {
    func photoOutput(_ output: AVCapturePhotoOutput,didFinishProcessingPhoto photo: AVCapturePhoto,error: Error?) {
        //If photo Failed to be captured
        guard error == nil else{
            print("Failed to capture photo")
            print(error?.localizedDescription as Any)
            return
        }
        //If pixel buffer Could not be converted to image data
        guard let imageData = photo.fileDataRepresentation() else {
            print("Fail to convert image data to UIImage")
            return
        }
        //If the UIImage Could not be initalized with image data
        guard let capturedImage = UIImage.init(data: imageData,scale: 1.0) else{
            print("fail to convert image data to UIImage")
            return
        }
        UIImageWritetoSavedPhotosAlbum(capturedImage,nil,nil)
        //displayCapturedPhoto(capturedPhoto: imagetoSave)
    }
}

我在其他帖子中看到 AVLayerVideoGravity.resizeAspectFill 已经为一些用户修复了它,所以任何关于为什么它不起作用的解释都会非常有帮助 - 提前非常感谢!!!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。