2013-05-09 5 views
1

У меня есть приложение, которое является в основном видом, и когда пользователь нажимает кнопку, начинается визуализация камеры.Изменение ориентации камеры и устройства

Я хочу разрешить все ориентации, когда камера не отображается, но когда камера отображается, мне нужно заставить приложение работать в портретном режиме, потому что, если он не находится в режиме «Портрет», видео поворачивается. Когда камера закрыта, приложение может снова вращаться.

Знаете ли вы, если я могу решить проблему с ориентацией видео?

Или как я могу заставить приложение работать в портретном режиме? Я знаю, что на более ранней версии ios вы можете использовать [UIDevice setOrientation:], но он устарел для последних ios.

Как это сделать для ios 5 и ios 6?

Я попытался с:

[self presentViewController:[UIViewController new] animated:NO 
completion:^{ [self dismissViewControllerAnimated:NO completion:nil]; }]; 

И в методе shouldAutorotateToInterfaceOrientation:

if (state == CAMERA) { 
     return (interfaceOrientation == UIInterfaceOrientationPortrait); 
    }else{ 
     return YES; 
} 

Он работает нормально и заставить приложение к портрету. Но когда камера закрыта, она работает неправильно, она не вращается хорошо.

Я имею в виду, когда камера закрыта, это то, что происходит:

  • приложение на портрете
  • Если я пытаюсь повернуть приложение, устройство вращается, но не приложение. Я вижу, что строка состояния ipad с информацией о времени, батарее и т. Д. Вращается, но приложение не работает.
  • Если я снова вернусь к портрету, а затем вращаю устройство, он работает нормально.

Вы знаете, что может быть проблемой?

Заранее спасибо.

ответ

3

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

Я вызываю этот код при инициализации камеры, а также в методе toAutorotateToInterfaceOrientation, где я допускаю все ориентации.

AVCaptureVideoOrientation newOrientation; 

    UIInterfaceOrientation deviceOrientation = [UIApplication sharedApplication].statusBarOrientation; 

    NSLog(@"deviceOrientation %c",deviceOrientation); 

    switch (deviceOrientation) 
    { 
     case UIInterfaceOrientationPortrait: 
      NSLog(@"UIInterfaceOrientationPortrait"); 
      newOrientation = AVCaptureVideoOrientationPortrait; 
      break; 
     case UIInterfaceOrientationLandscapeRight: 
      NSLog(@"UIInterfaceOrientationLandscapeRight"); 
      newOrientation = AVCaptureVideoOrientationLandscapeRight; 
      break; 
     case UIInterfaceOrientationLandscapeLeft: 
      NSLog(@"UIInterfaceOrientationLandscapeLeft"); 
      newOrientation = AVCaptureVideoOrientationLandscapeLeft; 
      break; 
     default: 
      NSLog(@"default"); 
      newOrientation = AVCaptureVideoOrientationPortrait; 
      break; 
    } 

    if ([self.prevLayer respondsToSelector:@selector(connection)]){ 
     if ([self.prevLayer.connection isVideoOrientationSupported]){ 
      self.prevLayer.connection.videoOrientation = newOrientation; 
     }else{ 
      NSLog(@"NO respond to selector connection"); 
     } 
    }else{ 


if ([self.prevLayer isOrientationSupported]){ 
     self.prevLayer.orientation = newOrientation; 
    }else{ 
     NSLog(@"NO isOrientationSupported"); 
    } 

} 
1

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

- (void)encodeVideoOrientation:(NSURL *)anOutputFileURL 
    { 
    CGAffineTransform rotationTransform; 
    CGAffineTransform rotateTranslate; 
    CGSize renderSize; 

    switch (self.recordingOrientation) 
    { 
     // set these 3 values based on orientation 

    } 


    AVURLAsset * videoAsset = [[AVURLAsset alloc]initWithURL:anOutputFileURL options:nil]; 

    AVAssetTrack *sourceVideoTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]; 
    AVAssetTrack *sourceAudioTrack = [[videoAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0]; 

    AVMutableComposition* composition = [AVMutableComposition composition]; 

    AVMutableCompositionTrack *compositionVideoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid]; 
    [compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) 
            ofTrack:sourceVideoTrack 
            atTime:kCMTimeZero error:nil]; 
    [compositionVideoTrack setPreferredTransform:sourceVideoTrack.preferredTransform]; 

    AVMutableCompositionTrack *compositionAudioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio 
                       preferredTrackID:kCMPersistentTrackID_Invalid]; 
    [compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) 
            ofTrack:sourceAudioTrack 
            atTime:kCMTimeZero error:nil]; 



    AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction]; 
    AVMutableVideoCompositionLayerInstruction *layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:compositionVideoTrack]; 
    [layerInstruction setTransform:rotateTranslate atTime:kCMTimeZero]; 

    AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoComposition]; 
    videoComposition.frameDuration = CMTimeMake(1,30); 
    videoComposition.renderScale = 1.0; 
    videoComposition.renderSize = renderSize; 
    instruction.layerInstructions = [NSArray arrayWithObject: layerInstruction]; 
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, videoAsset.duration); 
    videoComposition.instructions = [NSArray arrayWithObject: instruction]; 

    AVAssetExportSession * assetExport = [[AVAssetExportSession alloc] initWithAsset:composition 
                      presetName:AVAssetExportPresetMediumQuality]; 

    NSString* videoName = @"export.mov"; 
    NSString *exportPath = [NSTemporaryDirectory() stringByAppendingPathComponent:videoName]; 

    NSURL * exportUrl = [NSURL fileURLWithPath:exportPath]; 

    if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) 
    { 
     [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil]; 
    } 

    assetExport.outputFileType = AVFileTypeMPEG4; 
    assetExport.outputURL = exportUrl; 
    assetExport.shouldOptimizeForNetworkUse = YES; 
    assetExport.videoComposition = videoComposition; 

    [assetExport exportAsynchronouslyWithCompletionHandler: 
    ^(void) { 
     switch (assetExport.status) 
     { 
      case AVAssetExportSessionStatusCompleted: 
       //    export complete 
       NSLog(@"Export Complete"); 
       break; 
      case AVAssetExportSessionStatusFailed: 
       NSLog(@"Export Failed"); 
       NSLog(@"ExportSessionError: %@", [assetExport.error localizedDescription]); 
       //    export error (see exportSession.error) 
       break; 
      case AVAssetExportSessionStatusCancelled: 
       NSLog(@"Export Failed"); 
       NSLog(@"ExportSessionError: %@", [assetExport.error localizedDescription]); 
       //    export cancelled 
       break; 
     } 
    }]; 

    } 

Надеюсь, это поможет вам. !!

+0

Большое спасибо за ваш быстрый ответ. Извините, я новичок в программировании на ios, и я не понимаю, как я могу использовать ваш код. Где я должен это выразить? Что оно делает? Еще раз спасибо. –

Смежные вопросы