2015-10-14 150 views
0

我正在使用AvFoundation作为相机。使用avfoundation捕捉图像

这是我的实时预览:

enter image description here

看起来不错。当用户按下“按钮”时,我在同一屏幕上创建一个快照。 (像snapchat)

我使用的捕捉图像,并显示在屏幕上它下面的代码:

self.stillOutput.captureStillImageAsynchronouslyFromConnection(videoConnection){ 
         (imageSampleBuffer : CMSampleBuffer!, _) in 

         let imageDataJpeg = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageSampleBuffer) 
         let pickedImage: UIImage = UIImage(data: imageDataJpeg)! 
         self.captureSession.stopRunning() 
         self.previewImageView.frame = CGRect(x:0, y:0, width:UIScreen.mainScreen().bounds.width, height:UIScreen.mainScreen().bounds.height) 
         self.previewImageView.image = pickedImage 
         self.previewImageView.layer.zPosition = 100 
} 

用户后拍摄的图像画面看起来是这样的:

enter image description here

请看看标记的区域。它没有在实时预览屏幕上查看(屏幕截图1)。

我的意思是实时预览不显示一切。但我确定我的实时预览效果很好,因为我与其他相机应用程序相比,并且所有内容都与我的实时预览屏幕相同。我想我拍摄的图像有问题。

我创建实时预览与下面的代码:

override func viewWillAppear(animated: Bool) { 
    super.viewWillAppear(animated) 
    captureSession.sessionPreset = AVCaptureSessionPresetPhoto 
    let devices = AVCaptureDevice.devices() 
    for device in devices { 
     // Make sure this particular device supports video 
     if (device.hasMediaType(AVMediaTypeVideo)) { 
      // Finally check the position and confirm we've got the back camera 
      if(device.position == AVCaptureDevicePosition.Back) { 
       captureDevice = device as? AVCaptureDevice 
      } 
     } 
    } 
    if captureDevice != nil { 
     beginSession() 
    } 
} 

func beginSession() { 
    let err : NSError? = nil 
    do { 
     try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice)) 
    } catch{ 

    } 
    captureSession.addOutput(stillOutput) 
    if err != nil { 
     print("error: \(err?.localizedDescription)") 
    } 

    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) 
    previewLayer?.videoGravity=AVLayerVideoGravityResizeAspectFill 

    self.cameraLayer.layer.addSublayer(previewLayer!) 
    previewLayer?.frame = self.cameraLayer.frame 
    captureSession.startRunning() 
} 

cameraLayer

enter image description here

我怎样才能解决这个问题呢?

回答

0

想必您使用的是AVCaptureVideoPreviewLayer。所以它听起来像这个图层放置不正确或尺寸不正确,或者它具有错误的AVLayerVideoGravity设置。部分图像不在屏幕上或被裁剪;这就是为什么你在预览时看不到相机看到的部分。

+0

如果您需要更多帮助,那么您需要查看代码的一部分:您如何创建AVCaptureVideoPreviewLayer并将其显示在屏幕上? – matt

0

好吧,我找到了解决方案。

我用

captureSession.sessionPreset = AVCaptureSessionPresetHigh 

而不是

captureSession.sessionPreset = AVCaptureSessionPresetPhoto 

然后问题解决。