Как записать видео на экран в альбомном приложении? - PullRequest
4 голосов
/ 23 октября 2011

Это делает мою голову.

Я работаю в этом примере проекта: https://github.com/jj0b/AROverlayExample

Это отлично работает. Единственная проблема - это портретное приложение. Поэтому, когда я поворачиваю устройство в альбомную ориентацию, видео по-прежнему отображается так, как нужно, но все мои метки и пользовательский интерфейс теперь сбоку.

enter image description here

Чтобы исправить это, я устанавливаю ландшафт только в info.plist

Проблема заключается в следующем:

enter image description here

Вот мой код:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if (self) 
    {
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

        assert( self.autoresizesSubviews );


        CGPoint layerRectCenter = CGPointMake( CGRectGetMidX( frame ),
                                              CGRectGetMidY( frame ) );


        // Initialization code
        self.captureSession = [[[AVCaptureSession alloc] init] autorelease];

        // addVideoInput
        {
            AVCaptureDevice* videoDevice = [AVCaptureDevice defaultDeviceWithMediaType: AVMediaTypeVideo];  
            if (videoDevice) 
            {
                NSError *error;
                AVCaptureDeviceInput* videoIn = [AVCaptureDeviceInput deviceInputWithDevice: videoDevice error:&error];
                if ( ! error ) 
                {
                    if ( [self.captureSession canAddInput:videoIn] )
                        [self.captureSession addInput:videoIn];
                    else
                        NSLog(@"Couldn't add video input");     
                }
                else
                    NSLog(@"Couldn't create video input");
            }
            else
                NSLog(@"Couldn't create video capture device");
        }

        // addVideoPreviewLayer 
        {
            self.previewLayer = [[[AVCaptureVideoPreviewLayer alloc] initWithSession: self.captureSession] autorelease];
            self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

            self.previewLayer.frame = CGRectMake(0, 0, 480, 300); 
            self.previewLayer.orientation = AVCaptureVideoOrientationLandscapeRight;


            //self.previewLayer.frame = frame;

            [self.layer addSublayer: self.previewLayer];
        }

        // run!
        [self.captureSession startRunning];

    }
    return self;
}

Я не могу понять, почему видео отображается вбок, и, несмотря на специальную настройку рамки слоев в альбомную ориентацию CGRectMake (0, 0, 480, 300), оно получается наоборот.

1 Ответ

2 голосов
/ 24 октября 2011

Очень аккуратное решение - добавить представление непосредственно в окно.

Лучше всего это сделать в контроллере корневого представления:

// need to add the capture view to the window here: can't do it in viewDidLoad as the window is not ready at that point
- (void) viewDidAppear: (BOOL) animated
{
    self.frontCamView = [[[FrontCamView alloc] 
                          initWithFrame: [UIScreen mainScreen].bounds] 
                         autorelease];

    self.view.opaque = NO;
    self.view.backgroundColor = [UIColor clearColor];

    [self.view.window addSubview: self.frontCamView];
    [self.view.window sendSubviewToBack: self.frontCamView];
}

Затем реализацияСам вид камеры:

@interface FrontCamView ( )

@property (retain) AVCaptureVideoPreviewLayer* previewLayer;
@property (retain) AVCaptureSession* captureSession;

@end

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

@implementation FrontCamView

@synthesize captureSession;
@synthesize previewLayer;

// - - - 

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if (self) 
    {
        self.captureSession = [[[AVCaptureSession alloc] init] autorelease];

        // addVideoInput
        {
            AVCaptureDevice* videoDevice = [AVCaptureDevice defaultDeviceWithMediaType: AVMediaTypeVideo];  
            if (videoDevice) 
            {
                NSError *error;
                AVCaptureDeviceInput* videoIn = [AVCaptureDeviceInput deviceInputWithDevice: videoDevice error:&error];
                if ( ! error ) 
                {
                    if ( [self.captureSession canAddInput:videoIn] )
                        [self.captureSession addInput:videoIn];
                    else
                        NSLog(@"Couldn't add video input");     
                }
                else
                    NSLog(@"Couldn't create video input");
            }
            else
                NSLog(@"Couldn't create video capture device");
        }

        // addVideoPreviewLayer 
        {
            CGRect screenRect = [UIScreen mainScreen].bounds;

            self.previewLayer = [[[AVCaptureVideoPreviewLayer alloc] initWithSession: self.captureSession] autorelease];

            self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
            self.previewLayer.frame = screenRect;  
            self.previewLayer.orientation = AVCaptureVideoOrientationPortrait;         

            [self.layer addSublayer: self.previewLayer];

        }

        // run!
        [self.captureSession startRunning];

    }
    return self;
}

- (void) dealloc 
{
    [self.captureSession stopRunning];

    [previewLayer release], previewLayer = nil;
    [captureSession release], captureSession = nil;


    [super dealloc];
}

@end
...