iOS 整体项目竖屏 相机横屏

//横屏方法:

AppDelegate.m 中添加监听

//监听页面翻转

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setOrientationPortrait:) name:KNotification_setOrientationPortrait object:nil];

    

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setOrientationLandscape:) name:KNotification_setOrientationLandscape object:nil];


#pragma mark - UIInterfaceOrientation

- (UIInterfaceOrientationMask)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window{

    // iPhone doesn't support upside down by default, while the iPad does.  Override to allow all orientations always, and let the root view controller decide what's allowed (the supported orientations mask gets intersected).

    

    if (!_isPortrait) {

        return UIInterfaceOrientationMaskAll;

    }

    return UIInterfaceOrientationMaskPortrait;

}


- (void)setOrientationPortrait:(NSNotification *)aNotification{

    

    NSLog(@"Portrait");

    _isPortrait = YES;

}


- (void)setOrientationLandscape:(NSNotification *)aNotification{

    

    NSLog(@"Landscape");

    _isPortrait = NO;

    

    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {

        

        SEL selector = NSSelectorFromString(@"setOrientation:");

        

        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];

        

        [invocation setSelector:selector];

        

        [invocation setTarget:[UIDevice currentDevice]];

        

        int val =UIInterfaceOrientationPortrait;

        

        [invocation setArgument:&val atIndex:2];

        

        [invocation invoke];

    }

}


在需要横屏的时候

- (void)btnClicked{


    CustomImagePickerController *aCustomImagePickerController = [[CustomImagePickerController alloc]init];

    

    [[NSNotificationCenter defaultCenter]postNotificationName:KNotification_setOrientationLandscape object:nil];

    

    [self presentViewController:aCustomImagePickerController animated:YES completion:nil];

    

}


//实现session自定义相机代码转自网络

//

//  CustomImagePickerController.h

//

//  Created by SoldierTime on 15/10/22.

//  Copyright © 2015 HeLi. All rights reserved.


#import <UIKit/UIKit.h>

#import <AVFoundation/AVFoundation.h>


@class CustomImagePickerController;

@protocol CustomImagePickerControllerDelegate <NSObject>


- (void)customImagePickerController:(CustomImagePickerController *)picker didFinishPickingImage:(UIImage *)image;


@end


@interface CustomImagePickerController : UIViewController


@property(nonatomic)NSUInteger orietation;


@property (weak ,nonatomic) id <CustomImagePickerControllerDelegate> delegate;


@property (nonatomic, strong)       AVCaptureSession            * session;

//AVCaptureSession对象来执行输入设备和输出设备之间的数据传递


@property (nonatomic, strong)       AVCaptureDeviceInput        * videoInput;

//AVCaptureDeviceInput对象是输入流


@property (nonatomic, strong)       AVCaptureStillImageOutput   * stillImageOutput;

//照片输出流对象,当然我的照相机只有拍照功能,所以只需要这个对象就够了


@property (nonatomic, strong)       AVCaptureVideoPreviewLayer  * previewLayer;

//预览图层,来显示照相机拍摄到的画面


@property (nonatomic, strong)       UIBarButtonItem             * toggleButton;

//切换前后镜头的按钮


@property (nonatomic, strong)       UIButton                    * shutterButton;

//拍照按钮


@property (nonatomic, strong)       UIButton                    * cancelButton;

//取消按钮


@property (nonatomic, strong)       UIButton                    * doneButton;

//使用按钮


@property (nonatomic, strong)       UIView                      * cameraShowView;

//放置预览图层的View


@property (nonatomic, strong)       UIImageView                 * resultImageView;

//放置结果图层的View


@end



//

//  CustomImagePickerController.m

//

//  Created by SoldierTime on 15/10/22.

//  Copyright © 2015 HeLi. All rights reserved.

//


#import "CustomImagePickerController.h"


@interface CustomImagePickerController ()<UIImagePickerControllerDelegate>


@end


@implementation CustomImagePickerController


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    

    [self initialSession];

    

    //放置预览图层的View

    _cameraShowView = [[UIView alloc]init];

    _cameraShowView.frame = CGRectMake(0, 0 ,DTSCREEN_HEIGHT, DTSCREEN_WIDTH);

    [self.view addSubview:_cameraShowView];

    

    NSLog(@"%f %f",DTSCREEN_HEIGHT,DTSCREEN_WIDTH);

    

    //显示拍照结果

    _resultImageView = [[UIImageView alloc]init];

    _resultImageView.frame = CGRectMake(0, 0, 192, 108);

    [self.view addSubview:_resultImageView];

    

    //拍照按钮

    self.shutterButton = [UIButton buttonWithType:0];

    self.shutterButton.frame = CGRectMake(50, 200, 50, 50);

    self.shutterButton.backgroundColor = DTRGBACOLOR(100, 100, 100, 0.2);

    [self.view addSubview:self.shutterButton];

    

    [self.shutterButton addTarget:self action:@selector(shutterCamera) forControlEvents:UIControlEventTouchUpInside];

    

    //使用按钮

    self.doneButton = [UIButton buttonWithType:0];

    self.doneButton.frame = CGRectMake(150, 200, 50, 50);

    self.doneButton.backgroundColor = DTRGBACOLOR(0, 100, 0, 0.2);

    [self.view addSubview:self.doneButton];

    

    [self.doneButton addTarget:self action:@selector(finishPicking) forControlEvents:UIControlEventTouchUpInside];

    

    //取消按钮

    self.cancelButton = [UIButton buttonWithType:0];

    self.cancelButton.frame = CGRectMake(250, 200, 50, 50);

    self.cancelButton.backgroundColor = DTRGBACOLOR(100, 0, 0, 0.2);

    [self.view addSubview:self.cancelButton];

    

    [self.cancelButton addTarget:self action:@selector(closeView) forControlEvents:UIControlEventTouchUpInside];

    

}


- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];

    

    [self setUpCameraLayer];

}


- (void) viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];

    

    if (self.session) {

        [self.session startRunning];

    }

}


- (void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];

}


- (void) viewDidDisappear:(BOOL)animated{

    [super viewDidDisappear: animated];

    

    if (self.session) {

        [self.session stopRunning];

    }

}


- (void) initialSession{

    

    //这个方法的执行我放在init方法里了

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

    self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self backCamera] error:nil];

//    [self fronCamera]方法会返回一个AVCaptureDevice对象,因为我初始化时是采用前摄像头,所以这么写,具体的实现方法后面会介绍

    

    self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];

    NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];

    //这是输出流的设置参数AVVideoCodecJPEG参数表示以JPEG的图片格式输出图片

    [self.stillImageOutput setOutputSettings:outputSettings];

    

    if ([self.session canAddInput:self.videoInput]) {

        [self.session addInput:self.videoInput];

    }

    

    if ([self.session canAddOutput:self.stillImageOutput]) {

        [self.session addOutput:self.stillImageOutput];

    }

    

    AVCaptureConnection *output2VideoConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];

    output2VideoConnection.videoOrientation = [self videoOrientationFromCurrentDeviceOrientation];

}


- (void) setUpCameraLayer{

        

    if (self.previewLayer == nil) {

        

        self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];

        UIView * view = self.cameraShowView;

        CALayer * viewLayer = [view layer];

        [viewLayer setMasksToBounds:YES];


        [self.previewLayer setFrame:CGRectMake(0, 0, DTSCREEN_WIDTH, DTSCREEN_HEIGHT)];

        [self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];

        self.previewLayer.connection.videoOrientation = [self videoOrientationFromCurrentDeviceOrientation];

        

        [viewLayer insertSublayer:self.previewLayer below:[[viewLayer sublayers] objectAtIndex:0]];

    }

}



- (AVCaptureVideoOrientation) videoOrientationFromCurrentDeviceOrientation {

    

    switch (self.interfaceOrientation) {

        case UIInterfaceOrientationPortrait: {

            return AVCaptureVideoOrientationPortrait;

        }

        case UIInterfaceOrientationLandscapeLeft: {

           return AVCaptureVideoOrientationLandscapeLeft;

        }

        case UIInterfaceOrientationLandscapeRight: {

            return AVCaptureVideoOrientationLandscapeRight;

        }

        case UIInterfaceOrientationPortraitUpsideDown: {

            return AVCaptureVideoOrientationPortraitUpsideDown;

        }

    }

    

    return AVCaptureVideoOrientationLandscapeLeft;

}


- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition) position {

    

    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];

    for (AVCaptureDevice *device in devices) {

        if ([device position] == position) {

            return device;

        }

    }

    return nil;

}


- (AVCaptureDevice *)frontCamera {

    return [self cameraWithPosition:AVCaptureDevicePositionFront];

}


- (AVCaptureDevice *)backCamera {

    return [self cameraWithPosition:AVCaptureDevicePositionBack];

}


#pragma mark - actions


- (void)closeView{


    [[NSNotificationCenter defaultCenter]postNotificationName:@"setOrientationPortrait" object:nil];

    

    [self dismissViewControllerAnimated:YES completion:^{

    

    }];

}


- (void)toggleCamera {

    NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];

    if (cameraCount > 1) {

        NSError *error;

        AVCaptureDeviceInput *newVideoInput;

        AVCaptureDevicePosition position = [[_videoInput device] position];

        

        if (position == AVCaptureDevicePositionBack)

            newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self frontCamera] error:&error];

        else if (position == AVCaptureDevicePositionFront)

            newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self backCamera] error:&error];

        else

            return;

        

        if (newVideoInput != nil) {

            [self.session beginConfiguration];

            [self.session removeInput:self.videoInput];

            if ([self.session canAddInput:newVideoInput]) {

                [self.session addInput:newVideoInput];

                [self setVideoInput:newVideoInput];

            } else {

                [self.session addInput:self.videoInput];

            }

            [self.session commitConfiguration];

        } else if (error) {

            NSLog(@"toggle carema failed, error = %@", error);

        }

    }

}


- (void) shutterCamera{

    

    AVCaptureConnection * videoConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];

    if (!videoConnection) {

        NSLog(@"take photo failed!");

        return;

    }

    

    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {

        if (imageDataSampleBuffer == NULL) {

            return;

        }

        NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];

        UIImage * image = [UIImage imageWithData:imageData];

        self.resultImageView.image = image;

        NSLog(@"image size = %@",NSStringFromCGSize(image.size));

    }];

}


- (void)finishPicking{

    

    if (_delegate) {

        

        [_delegate customImagePickerController:self didFinishPickingImage:self.resultImageView.image];

    }

    

    [self closeView];


}


#pragma mark Orientations

- (BOOL)shouldAutorotate{

    

    return NO;

}



- (UIInterfaceOrientationMask)supportedInterfaceOrientations{

    

    return UIInterfaceOrientationMaskLandscape;

}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{

    

    return (interfaceOrientation != UIInterfaceOrientationLandscapeLeft

            || interfaceOrientation != UIInterfaceOrientationLandscapeRight);

}



- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


/*

#pragma mark - Navigation


// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/


@end




  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值