Пейзаж в AvCam iOS 6

Я новичок в iOS, пытаюсь создать собственную камеру с помощью AvCam. У меня проблемы с предварительным просмотром в альбомной ориентации - изображение поворачивается на 90 градусов по часовой стрелке и отображается на половине экрана.

Я получаю это сообщение -

ВНИМАНИЕ: - [setOrientation:] устарел.

Используйте AVCaptureConnection -setVideoOrientation:

AVCaptureConnection уже устанавливает ориентацию, поэтому я понятия не имею, что мне еще нужно.

Я знаю, что этот вопрос задавали много раз для предыдущих версий iOS (4,5), но ни один из этих методов / кодов у меня не работал (iOS 6).

Исходный код (без изменений от Apple)

if ([self captureManager] == nil) {
    AVCamCaptureManager *manager = [[AVCamCaptureManager alloc] init];
    [self setCaptureManager:manager];
    [manager release];

    [[self captureManager] setDelegate:self];

    if ([[self captureManager] setupSession]) {
        // Create video preview layer and add it to the UI
        AVCaptureVideoPreviewLayer *newCaptureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:[[self captureManager] session]];


        UIView *view = [self videoPreviewView];
        CALayer *viewLayer = [view layer];
        [viewLayer setMasksToBounds:YES];

        CGRect bounds = [view bounds];
        [newCaptureVideoPreviewLayer setFrame:bounds];

        if ([newCaptureVideoPreviewLayer isOrientationSupported]) {
            [newCaptureVideoPreviewLayer setOrientation:AVCaptureVideoOrientationPortrait];
        }



        [newCaptureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];

        [viewLayer insertSublayer:newCaptureVideoPreviewLayer below:[[viewLayer sublayers] objectAtIndex:0]];

        [self setCaptureVideoPreviewLayer:newCaptureVideoPreviewLayer];

Блок AVCaptureConnection:

-(void)startRecordingWithOrientation:(AVCaptureVideoOrientation)videoOrientation; {
AVCaptureConnection *videoConnection = [AVCamUtilities connectionWithMediaType:AVMediaTypeVideo fromConnections:[[self movieFileOutput] connections]];
if ([videoConnection isVideoOrientationSupported])
    [videoConnection setVideoOrientation:videoOrientation];

[[self movieFileOutput] startRecordingToOutputFileURL:[self outputFileURL] recordingDelegate:self];

}


person Laz    schedule 19.10.2012    source источник


Ответы (2)


В прошлый раз я тоже наткнулся на эту проблему. Я решил эту проблему, выполнив две вещи

  1. Получение правильной ориентации
    Заменить

    if ([newCaptureVideoPreviewLayer isOrientationSupported]) {
        [newCaptureVideoPreviewLayer setOrientation:AVCaptureVideoOrientationPortrait];
    }  
    

    С участием

    if ([newCaptureVideoPreviewLayer.connection isVideoOrientationSupported]) {  
        [newCaptureVideoPreviewLayer.connection setVideoOrientation:[UIDevice currentDevice].orientation];
    }
    
  2. Принудительно обновить ориентацию видео во время инициализации, чтобы захватить вывод видео в альбомном режиме, запустив - (void)deviceOrientationDidChange вручную в AVCaptureManager.m

    Я добавил это в:

    - (BOOL) setupSession
    {
        BOOL success = NO;
    
        ...
    
        AVCamRecorder *newRecorder = [[AVCamRecorder alloc] initWithSession:[self session] outputFileURL:self.lastOutputfileURL];
        [newRecorder setDelegate:self];
    
        [self performSelector:@selector(deviceOrientationDidChange)];
    
        ...
    
        return success;
    }
    
person Simon D.    schedule 05.08.2013

Итак, вот обходной путь, но я уверен, что должно быть лучшее решение, чем это. Я получил часть кода из этого вопроса:

Приложение для iPhone - отображение видео AVFoundation в ландшафтном режиме

Но пришлось настроить фрейм для каждой ориентации, чтобы он работал на iOS6 (и он все еще показывает предупреждение):


- (void) willAnimateRotationToInterfaceOrientation: (UIInterfaceOrientation) toInterfaceOrientation duration: (NSTimeInterval) duration {

[CATransaction begin];
if (toInterfaceOrientation==UIInterfaceOrientationLandscapeLeft){
    captureVideoPreviewLayer.orientation = UIInterfaceOrientationLandscapeLeft;
    captureVideoPreviewLayer.frame = CGRectMake(0, 0, 480, 320);

} else if (toInterfaceOrientation==UIInterfaceOrientationPortrait){
    captureVideoPreviewLayer.orientation = UIInterfaceOrientationPortrait;
    captureVideoPreviewLayer.frame = CGRectMake(0, 0, 320, 480);

} else if (toInterfaceOrientation==UIInterfaceOrientationLandscapeRight){
    captureVideoPreviewLayer.orientation = UIInterfaceOrientationLandscapeRight;
    captureVideoPreviewLayer.frame = CGRectMake(0, 0, 480, 320);

}
[CATransaction commit];
[super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];

}

person Laz    schedule 19.10.2012
comment
В этом потоке есть решение для устранения предупреждения об ориентации - http://stackoverflow.com/questions/11532337/isorientationsupported-is-deprecated-in-ios - person Laz; 09.11.2012