AVCaptureVideoPreviewLayer не заполняет экран

Я прочитал около миллиона тем о том, как сделать VideoPreviewLayer, заполняющий весь экран iPhone, но ничего не работает ... возможно, вы можете мне помочь, потому что я действительно застрял.

Это моя инициализация слоя предварительного просмотра:

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
    // Choosing bigger preset for bigger screen.
    _sessionPreset = AVCaptureSessionPreset1280x720;
}
else
{
    _sessionPreset = AVCaptureSessionPresetHigh;
}

[self setupAVCapture];

AVCaptureSession *captureSession = _session;
AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:captureSession];
UIView *aView = self.view;
previewLayer.frame = aView.bounds;
previewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
[aView.layer addSublayer:previewLayer];

Это мой метод setupAvCapture:

  //-- Setup Capture Session.
_session = [[AVCaptureSession alloc] init];
[_session beginConfiguration];

//-- Set preset session size.
[_session setSessionPreset:_sessionPreset];

//-- Creata a video device and input from that Device.  Add the input to the capture session.
AVCaptureDevice * videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if(videoDevice == nil)
    assert(0);

//-- Add the device to the session.
NSError *error;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
if(error)
    assert(0);

[_session addInput:input];

//-- Create the output for the capture session.
AVCaptureVideoDataOutput * dataOutput = [[AVCaptureVideoDataOutput alloc] init];
[dataOutput setAlwaysDiscardsLateVideoFrames:YES]; // Probably want to set this to NO when recording

//-- Set to YUV420.
[dataOutput setVideoSettings:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_420YpCbCr8BiPlanarFullRange]
                                                         forKey:(id)kCVPixelBufferPixelFormatTypeKey]]; // Necessary for manual preview

// Set dispatch to be on the main thread so OpenGL can do things with the data
[dataOutput setSampleBufferDelegate:self queue:dispatch_get_main_queue()];

[_session addOutput:dataOutput];
[_session commitConfiguration];

[_session startRunning];

Я уже пытался использовать разные параметры AVCaptureSessionPresets и ResizeFit. Но это всегда выглядит так:

http://imageshack.us/photo/my-images/707/img0013g.png/

Или это, если я использую previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill; Если я регистрирую размер слоя, возвращается правильный полноэкранный размер.

http://imageshack.us/photo/my-images/194/img0014k.png/


person user2135074    schedule 26.04.2013    source источник
comment
Если я установлю previewLayer.frame = CGRectMake(0, 0, 1280, 720); вручную это работает ... может ли кто-нибудь объяснить это. Кажется, что ширина/высота перевернуты (книжная), но на самом деле ориентация альбомная. Так что я могу исправить эту реализацию _screenWidth = [UIScreen mainScreen].bounds.size.width; _screenHeight = [UIScreen mainScreen].bounds.size.height; if(_screenHeight › _screenWidth){ _screenWidth = _screenHeight; _screenHeight = [UIScreen mainScreen].bounds.size.width; }   -  person user2135074    schedule 26.04.2013


Ответы (2)


пытаться:

AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [AVCaptureVideoPreviewLayer layerWithSession: self.session];
[captureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];

Быстрое обновление

let previewLayer = AVCaptureVideoPreviewLayer(session: session)
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill

Обновление Swift 4.0

let previewLayer = AVCaptureVideoPreviewLayer(session: session)
previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
person Gabriel.Massana    schedule 22.10.2014
comment
Это работает при первой загрузке. Но повторное применение при ротации, похоже, не делает того, что нужно. - person mattdeboard; 13.07.2015
comment
возможно, вам следует остановить вращение камеры предварительного просмотра. Сделайте прозрачный вид над предварительным просмотром для кнопок, которые вы собираетесь разместить, и оставьте его вращающимся. Я думаю, что поворот предварительного просмотра камеры довольно забавен, и приведенный выше правильный ответ. :) - person Nikolay; 08.09.2015

Если у кого-то возникла эта проблема, вам нужно просто выйти за пределы экрана.

    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    previewLayer.frame = UIScreen.main.bounds
    previewLayer.videoGravity = .resizeAspectFill
    camPreview.layer.addSublayer(previewLayer)
person Ahmed Safadi    schedule 08.02.2020