AVCaptureVideoOrientation存在问题,错误地显示相机预览

时间:2014-05-06 07:30:02

标签: ios iphone camera rotation

我已经从2011年获得了一些代码来更新客户端,我已经设法将其全部分类为iOS7等,并将更新提交给Apple。

我现在有一个应用程序的问题,我需要尽快解决。我真的很难找到解决方案,我已经尝试了各种各样的方法!

简而言之,此应用程序允许用户在自定义相机视图中拍摄多张照片(始终使用相机预览),然后点击完成按钮关闭窗口并返回上一屏幕。

然而,当相机预览显示在屏幕上时,它的方向不正确,逆时针旋转90度。

这是一个例子......

Photo example of camera issue

我需要强制用户以横向模式拍摄照片。

第二个问题是如果用户拍摄风景照片,它也会逆时针方向保存90度。

任何人都可以帮忙????

下面是完整的代码,这是使用提供的原始代码,只需进行一些调整即可轻松修复它!

非常感谢提前

西蒙

//
//  CameraViewController.m
//  X
//
//  Created by X on 8/9/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CameraViewController.h"
#import <ImageIO/ImageIO.h>




static AVCaptureVideoOrientation avOrientationForInterfaceOrientation(UIInterfaceOrientation iOrientation);

static AVCaptureVideoOrientation avOrientationForInterfaceOrientation(UIInterfaceOrientation iOrientation)
{
    AVCaptureVideoOrientation result = iOrientation;
    if ( iOrientation == UIInterfaceOrientationLandscapeLeft )
        result = AVCaptureVideoOrientationLandscapeLeft;
    else if ( iOrientation == UIInterfaceOrientationLandscapeRight )
        result = AVCaptureVideoOrientationLandscapeRight;
    return result;
}





@implementation CameraViewController
@synthesize stillImageOutput, delegate;
@synthesize session, captureVideoPreviewLayer;


- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    AVCaptureVideoOrientation avcaptureOrientation = avOrientationForInterfaceOrientation(toInterfaceOrientation);
    self.captureVideoPreviewLayer.connection.videoOrientation =  avcaptureOrientation;
}


- (void)dealloc {
    [stillImageOutput release];
    [captureVideoPreviewLayer release];
    [session release];

    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

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

    // rotate the status bar
    [UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationLandscapeLeft;

    // try and rotate the camera live preview


}


-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    self.session = [[AVCaptureSession alloc] init];
    session.sessionPreset = AVCaptureSessionPresetMedium;

    self.captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    AVCaptureVideoOrientation avcaptureOrientation = avOrientationForInterfaceOrientation(self.interfaceOrientation);
    self.captureVideoPreviewLayer.connection.videoOrientation =  avcaptureOrientation;
    //captureVideoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
    NSLog(@"doing something");
    captureVideoPreviewLayer.frame = cameraView.bounds;


    [cameraView.layer addSublayer:captureVideoPreviewLayer];

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (!input) {
        // Handle the error appropriately.
        NSLog(@"ERROR: trying to open camera: %@", error);
    }
    [session addInput:input];

    stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
    [stillImageOutput setOutputSettings:outputSettings];

    [session addOutput:stillImageOutput];

    [session startRunning];

    canDismiss = 0;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didRotate:)
                                                 name:UIDeviceOrientationDidChangeNotification object:nil];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(BOOL)shouldAutorotate {
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscapeLeft;
}


// Set the camera to force itself to a landscape view
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationLandscapeLeft;
}


/*- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 //return (interfaceOrientation == UIInterfaceOrientationPortrait);
 return (interfaceOrientation == UIInterfaceOrientationPortrait) | (interfaceOrientation == UIInterfaceOrientationLandscapeLeft) | (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
 }*/

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{

    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
    {
        captureVideoPreviewLayer.connection.videoOrientation = UIInterfaceOrientationLandscapeLeft;
    }

    // and so on for other orientations
    return ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft));
}




- (void) didRotate:(NSNotification *)notification {
    [UIView beginAnimations:nil context:nil];

    if ( UIInterfaceOrientationIsLandscape([[UIDevice currentDevice] orientation]) ) {
        [topView setFrame:CGRectMake(0, 0, 320, 27)];
        [bottomView setFrame:CGRectMake(0, 453, 320, 27)];
    } else {
        [topView setFrame:CGRectMake(0, 0, 320, 110)];
        [bottomView setFrame:CGRectMake(0, 350, 320, 110)];
    }

    switch ([[UIDevice currentDevice] orientation]) {
        case UIInterfaceOrientationLandscapeLeft:
            btnDone.transform = CGAffineTransformMakeRotation(3*M_PI_2);
            btnTakePicture.transform = CGAffineTransformMakeRotation(3*M_PI_2);
            break;
        default:
            btnDone.transform = CGAffineTransformMakeRotation(M_PI_2);
            btnTakePicture.transform = CGAffineTransformMakeRotation(M_PI_2);
            break;
    }

    [UIView commitAnimations];
}

-(IBAction)takePhoto {
    AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in 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: %@", stillImageOutput);
    canDismiss++;
    [stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
     {
         CFDictionaryRef exifAttachments = CMGetAttachment( imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
         if (exifAttachments)
         {
             // Do something with the attachments.
             NSLog(@"attachements: %@", exifAttachments);
         }
         else
             NSLog(@"no attachments");

         int width = [[[NSUserDefaults standardUserDefaults] objectForKey:@"image_width"] intValue];
         int height = [[[NSUserDefaults standardUserDefaults] objectForKey:@"image_height"] intValue];

         NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
         UIImage * image = [[UIImage alloc] initWithData:imageData];
         NSLog(@"Image w:%f h:%f", image.size.width, image.size.height);
         UIImage * rotatedimage;
         if ( UIInterfaceOrientationIsLandscape([[UIDevice currentDevice] orientation]) ) {

             // Rotate the image
             CGSize newSize = CGSizeMake(image.size.height, image.size.width);
             CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
             CGContextRef ctx = CGBitmapContextCreate (NULL, newSize.width, newSize.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
             CGColorSpaceRelease(colorSpace);
             if ( [[UIDevice currentDevice] orientation] == UIInterfaceOrientationLandscapeLeft ) {
                 CGAffineTransform transform = CGAffineTransformMakeTranslation(0.0, newSize.height);
                 transform = CGAffineTransformScale(transform, 1.0, -1.0);

                 CGContextScaleCTM(ctx, -1.0, 1.0);
                 CGContextTranslateCTM(ctx, -newSize.width, 0);
                 CGContextConcatCTM(ctx, transform);
             }
             CGContextDrawImage(ctx, CGRectMake(0, 0, newSize.width, newSize.height), image.CGImage);
             CGImageRef sourceImageRef = CGBitmapContextCreateImage(ctx);
             rotatedimage = [UIImage imageWithCGImage:sourceImageRef];
             CGContextRelease(ctx);

             NSLog(@"Rotated Image w:%f h:%f", rotatedimage.size.width, rotatedimage.size.height);

             // Scale the image
             newSize = CGSizeMake(width, height);
             UIGraphicsBeginImageContext(newSize);
             [rotatedimage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
             //image is the original UIImage
             UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
             UIGraphicsEndImageContext();
             NSLog(@"New Image w:%f h:%f", newImage.size.width, newImage.size.height);
             [delegate tookPhoto:newImage];
         } else {
             // Scale the image
             CGSize newSize = CGSizeMake(width, image.size.height/(image.size.width/width));
             UIGraphicsBeginImageContext( newSize );
             [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
             UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
             UIGraphicsEndImageContext();
             NSLog(@"New Image w:%f h:%f", newImage.size.width, newImage.size.height);

             // Chop out the middle
             CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
             CGContextRef ctx = CGBitmapContextCreate (NULL, width, height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
             CGColorSpaceRelease(colorSpace);
             if ( [[UIDevice currentDevice] orientation] == UIInterfaceOrientationPortraitUpsideDown ) {
                 CGAffineTransform transform = CGAffineTransformMakeTranslation(0.0, newImage.size.height);
                 transform = CGAffineTransformScale(transform, 1.0, -1.0);

                 CGContextScaleCTM(ctx, -1.0, 1.0);
                 CGContextTranslateCTM(ctx, -newImage.size.width, 0);
                 CGContextConcatCTM(ctx, transform);
                 CGContextDrawImage(ctx, CGRectMake(0, (newImage.size.height-height)/2, newImage.size.width, newImage.size.height), newImage.CGImage);
             } else {
                 CGContextDrawImage(ctx, CGRectMake(0, -(newImage.size.height-height)/2, newImage.size.width, newImage.size.height), newImage.CGImage);
             }
             CGImageRef sourceImageRef = CGBitmapContextCreateImage(ctx);
             CGContextRelease(ctx);
             [delegate tookPhoto:[UIImage imageWithCGImage:sourceImageRef]];
         }
         [image release];

         canDismiss--;
     }];
}


// action when the 'tick' button is pressed
-(IBAction)done {
    if ( canDismiss == 0 ) {
        self.delegate = nil;

        // animate the camera view away
        [self dismissViewControllerAnimated:YES completion:nil];

        // swap the status bar back to the default portrait
        [UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationPortrait;
    }
}

@end

0 个答案:

没有答案