3

Im, использующий AVCaptureSession для съемки и хранения изображений в альбоме. Когда я нажимаю кнопку, она берет снимок и сохраняет альбом. Но когда я использую ландшафтный режим, то нажмите кнопку, в которой хранятся ландшафтные режимы, приводит к перевернутым неподвижным изображениям.AVCaptureVideoOrientation пейзажные режимы приводят к перевернутым неподвижным изображениям

enter image description here

код:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view. 

    [self setCaptureSession:[[AVCaptureSession alloc] init]]; 


    [self addVideoInputFrontCamera:NO]; // set to YES for Front Camera, No for Back camera 

    [self addStillImageOutput]; 

    [self setPreviewLayer:[[AVCaptureVideoPreviewLayer alloc] initWithSession:[self captureSession]] ]; 

     [[self previewLayer] setVideoGravity:AVLayerVideoGravityResizeAspectFill]; 

     CGRect layerRect = [[[self view] layer] bounds]; 


    [[self previewLayer]setBounds:layerRect]; 
    [[self previewLayer] setPosition:CGPointMake(CGRectGetMidX(layerRect),CGRectGetMidY(layerRect))]; 
    [[[self view] layer] addSublayer:[self previewLayer]]; 

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveImageToPhotoAlbum) name:kImageCapturedSuccessfully object:nil]; 


    [[self captureSession] startRunning]; 

camera=[UIButton buttonWithType:UIButtonTypeCustom]; 
[camera setImage:[UIImage imageNamed:@"button.png"] forState:UIControlStateNormal]; 
[camera setFrame:CGRectMake(150, 10, 40, 30)]; 
[camera addTarget:self action:@selector(takephoto:) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:camera]; 

} 

Кнопка для фотосъемки:

-(void)takephoto:(id)sender{ 

[self captureStillImage]; 

} 

- (void)captureStillImage 
{ 
    AVCaptureConnection *videoConnection = nil; 
    for (AVCaptureConnection *connection in [[self stillImageOutput] connections]) { 
     for (AVCaptureInputPort *port in [connection inputPorts]) { 
      if ([[port mediaType] isEqual:AVMediaTypeVideo]) { 
       videoConnection = connection; 
       break; 
      } 
     } 
     if (videoConnection) { 
      break; 
     } 
    } 

    NSLog(@"about to request a capture from: %@", [self stillImageOutput]); 

    [[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:videoConnection 
                 completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error) { 
                  CFDictionaryRef exifAttachments = CMGetAttachment(imageSampleBuffer, kCGImagePropertyExifDictionary, NULL); 
                  if (exifAttachments) { 
                   NSLog(@"attachements: %@", exifAttachments); 
                  } else { 
                   NSLog(@"no attachments"); 
                  } 

                  NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer]; 
                  UIImage *image = [[UIImage alloc] initWithData:imageData]; 


                  [self setStillImage:image]; 



                  // [image release]; 
                  [[NSNotificationCenter defaultCenter] postNotificationName:kImageCapturedSuccessfully object:nil]; 

                 }]; 


} 
+0

Я предлагаю вам прочитать: [Почему режимы ландшафтных AVCaptureVideoOrientation приводят вниз неподвижные изображения?] (Http://stackoverflow.com/questions/7845520/why-does-avcapturevideoorientation-landscape-modes-result- in-upside-down-still-i? rq = 1) – foundry

+0

@HeWas: Я уже видел это. Но я не понял, как это сделать? – user2474320

+0

@ user2474320 ... Я буду в сети весь день, но если у вас нет полезных ответов сегодня вечером, я дам u подробнее – foundry

ответ

6

Вы должны установить свойство videoOrientation в videoConnection, основанный на ориентации устройства. Сделайте это в captureStillImage, после того, как вы установили AVCaptureConnection.

UIDeviceOrientation deviceOrientation = 
        [[UIDevice currentDevice] orientation]; 
    AVCaptureVideoOrientation avcaptureOrientation; 
    if (deviceOrientation == UIDeviceOrientationLandscapeLeft) 
      avcaptureOrientation = AVCaptureVideoOrientationLandscapeRight; 

    else if (deviceOrientation == UIDeviceOrientationLandscapeRight) 
      avcaptureOrientation = AVCaptureVideoOrientationLandscapeLeft; 

    [videoConnection setVideoOrientation:avcaptureOrientation]; 
+1

Теперь читателю остается узнать, почему UI Landscape ** left ** переводится в AVCapture landscape ** right **. Apple полна сюрпризов! – Gui13

+2

Вот подсказка: устройство может иметь камеры с каждой стороны. Осталось ли для задней камеры левую для правильной камеры? –