| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591 |
- //
- // RACameraViewController.m
- // Apex And Drivers
- //
- // Created by Jack on 2018/6/5.
- // Copyright © 2018年 USAI. All rights reserved.
- //
- #import "RACameraViewController.h"
- #import <AVFoundation/AVFoundation.h>
- #import "RATakePhotoPreviewController.h"
- #import <CoreMotion/CoreMotion.h>
- #import "RAUtils.h"
- @interface RACameraViewController ()<AVCapturePhotoCaptureDelegate>
- @property (nonatomic,strong) IBOutlet UIView *previewContainer;
- @property (nonatomic,strong) IBOutlet UIView *controlContanier;
- @property (strong, nonatomic) IBOutlet UIButton *takePhotoBtn;
- @property (strong, nonatomic) IBOutlet UIButton *backBtn;
- @property (nonatomic,assign) BOOL barHidden;
- #pragma mark - Camera
- @property (nonatomic,strong) AVCaptureDevice *captureDevice;
- @property (nonatomic,strong) AVCaptureSession *captureSession;
- @property (nonatomic,strong) AVCaptureDeviceInput *captureInput;
- //@property (nonatomic,strong) AVCaptureStillImageOutput *captureOutput;
- @property (nonatomic,strong) AVCapturePhotoSettings *photoSetting;
- @property (nonatomic,strong) AVCapturePhotoOutput* photoOutput;
- @property (nonatomic,strong) AVCaptureVideoPreviewLayer *previewLayer;
- @property (nonatomic,assign) BOOL cameraInitial;
- @property (nonatomic,assign) AVLayerVideoGravity gravity;
- @property (strong, nonatomic) CMMotionManager *motionManager;
- @property (assign, nonatomic) UIDeviceOrientation orientationLast;
- @end
- @implementation RACameraViewController
- -(BOOL)shouldAutorotate {
- return NO;
- }
- - (void)initMotionManager
- {
- if (_motionManager == nil) {
- _motionManager = [[CMMotionManager alloc] init];
- }
-
- // 提供设备运动数据到指定的时间间隔
- _motionManager.deviceMotionUpdateInterval = .3;
-
- if (_motionManager.deviceMotionAvailable) { // 确定是否使用任何可用的态度参考帧来决定设备的运动是否可用
- [_motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue]
- withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
- if (!error) {
- [self outputAccelertionData:accelerometerData.acceleration];
- }
- else{
- NSLog(@"%@", error);
- }
- }];
-
-
- }else
- {
- [self setMotionManager:nil];
- }
- }
- - (void)outputAccelertionData:(CMAcceleration)acceleration{
- UIDeviceOrientation orientationNew;
- // NSLog(@"x %f y %f z %f",acceleration.x,acceleration.y, acceleration.z);
- if (acceleration.x >= 0.75) {
- orientationNew = UIDeviceOrientationLandscapeRight;
-
-
- }
- else if (acceleration.x <= -0.75) {
- orientationNew = UIDeviceOrientationLandscapeLeft;
- }
- else if (acceleration.y <= -0.75) {
- orientationNew = UIDeviceOrientationPortrait;
- }
- else if (acceleration.y >= 0.75) {
- orientationNew = UIDeviceOrientationPortraitUpsideDown;
- }
- else {
- // Consider same as last time
- return;
- }
- if (orientationNew == self.orientationLast)
- return;
- self.orientationLast = orientationNew;
-
- // [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:orientationNew] forKey:@"orientation"];
-
-
- // CGRect frame = self.previewContainer.bounds;
-
- // [self resetPreview:frame];
- }
- + (NSString *)storyboardID {
- return NSStringFromClass([self class]);
- }
- + (instancetype)viewControllerFromStoryboard {
- RACameraViewController *cameraVC = [[UIStoryboard storyboardWithName:@"Camera" bundle:nil] instantiateViewControllerWithIdentifier:[self storyboardID]];
- cameraVC.takeMode = RACameraTakeModeTakeOnce;
- cameraVC.gravity = AVLayerVideoGravityResizeAspectFill;
- return cameraVC;
- }
- + (instancetype)showCameraFromViewController:(UIViewController *)from withTakeMode:(RACameraTakeMode)mode videoGravity:(AVLayerVideoGravity)gravity completion:(void(^)(UIImage *image))completion {
-
- RACameraViewController *vc = [self viewControllerFromStoryboard];
- vc.takeMode = mode;
- if (!gravity) {
- gravity = AVLayerVideoGravityResizeAspectFill;
- }
- vc.gravity = gravity;
- vc.completion = completion;
- return vc;
- }
- - (void)viewDidLoad {
- [super viewDidLoad];
- // Do any additional setup after loading the view.
- [self initMotionManager];
- UIImage *normal_img = [self.class imageWithColor:[UIColor redColor] Size:CGSizeMake(60, 60)];
- UIImage *highlight_img = [self.class imageWithColor:[UIColor whiteColor] Size:CGSizeMake(60, 60)];
-
- [self.takePhotoBtn setImage:normal_img forState:UIControlStateNormal];
- [self.takePhotoBtn setImage:highlight_img forState:UIControlStateHighlighted];
-
- // [self initCapture];
- // [self initTakePicture];
-
- if ([self camerAuthorization]) {
-
- [self initCapture];
- [self initTakePicture];
-
- } else {
- // fix:第一次打开相机的时候授权成功后,未初始化相机
- [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
-
- dispatch_async(dispatch_get_main_queue(), ^{
- if (granted) {
- [self initCapture];
- [self initTakePicture];
-
- CGRect frame = self.previewContainer.bounds;
- [self resetPreview:CGRectOffset(frame, CGRectGetWidth(frame), 0)];
-
- [UIView animateWithDuration:0.3 animations:^{
- self.previewLayer.frame = frame;
- }];
-
- if (self.cameraInitial && !self.captureSession.isRunning) {
- // [self.captureSession startRunning];
-
-
- dispatch_async(dispatch_get_global_queue(0, 0), ^{
- [self.captureSession startRunning];
- // sleep(0.3);
- // dispatch_async(dispatch_get_main_queue(), ^{
- // [self.mask removeFromSuperview];
- // });
- });
- }
-
- } else {
-
- NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
- NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
- if (!appName) {
- appName = [infoDict objectForKey:@"CFBundleName"];
- }
- __weak typeof(self) weakSelf = self;
- UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Warning" message:[NSString stringWithFormat:@"Camera access denied, please change %@ setting, allow App use camera. (setting -> privacy -> camera enable %@)",[UIDevice currentDevice].model,appName] preferredStyle:UIAlertControllerStyleAlert];
- UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
- [weakSelf dismissViewControllerAnimated:YES completion:nil];
- }];
- [alert addAction:action];
- [self presentViewController:alert animated:YES completion:nil];
-
- }
- });
-
- }];
- }
- /**
- * 管理导航条
- * 在viewDidload的时候隐藏导航条
- * 恢复导航条的显示/隐藏有两个地方:1.退出的时候;2.确认使用照片的时候
- */
- if (self.navigationController) {
- BOOL navBarHidden = self.navigationController.navigationBar.hidden;
- self.barHidden = navBarHidden;
- if (!navBarHidden) {
- [self.navigationController setNavigationBarHidden:YES animated:YES];
- }
- }
- }
- - (void)didReceiveMemoryWarning {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- - (void)viewWillAppear:(BOOL)animated {
- [super viewWillAppear:animated];
-
- if (self.cameraInitial && !self.captureSession.isRunning) {
-
-
- dispatch_async(dispatch_get_global_queue(0, 0), ^{
- [self.captureSession startRunning];
- // sleep(0.3);
- // dispatch_async(dispatch_get_main_queue(), ^{
- // [self.mask removeFromSuperview];
- // });
- });
-
- }
- }
- - (void)viewWillDisappear:(BOOL)animated {
- [super viewWillDisappear:animated];
-
- if ([self.captureSession isRunning]) {
- [self.captureSession stopRunning];
- }
- }
- - (BOOL)prefersStatusBarHidden {
- return YES;
- }
- - (void)viewDidLayoutSubviews {
- [super viewDidLayoutSubviews];
-
- // 强制布局一次,不然 takePhotoBtn frame还没发生改变
- [self.controlContanier layoutIfNeeded];
-
- if ([self camerAuthorization] && self.cameraInitial) {
-
- CGRect frame = self.previewContainer.bounds;
- UIInterfaceOrientation orientation =[RAUtils query_orientation:self];
- BOOL isPortrait = /*self.interfaceOrientation*/orientation == UIInterfaceOrientationPortrait || /*self.interfaceOrientation*/orientation == UIInterfaceOrientationPortraitUpsideDown;
- // aspect ratio 3:4
- if (self.gravity == AVLayerVideoGravityResizeAspect) {
-
- CGRect backBtnFrame = [self.previewContainer convertRect:self.backBtn.frame fromView:self.controlContanier];
- CGRect captureBtnFrame = [self.previewContainer convertRect:self.takePhotoBtn.frame fromView:self.controlContanier];
-
- if (isPortrait) {
- CGFloat left = 0;
- CGFloat top = CGRectGetMaxY(backBtnFrame);
- CGFloat bottom = CGRectGetMinY(captureBtnFrame);
- CGFloat width = CGRectGetWidth(self.controlContanier.bounds);
- CGFloat height = bottom - top;
-
- frame = CGRectMake(left, top, width, height);
- } else {
-
- CGFloat left = CGRectGetMaxX(backBtnFrame);
- CGFloat right = CGRectGetMinX(captureBtnFrame);
- CGFloat top = 0;
- CGFloat width = right - left;
- CGFloat bottom = CGRectGetHeight(self.controlContanier.bounds);
- CGFloat height = bottom - top;
-
- frame = CGRectMake(left, top, width, height);
- }
- }
-
- [self resetPreview:frame];
- }
- }
- #pragma mark - Capture
- - (void)resetPreview:(CGRect)frame {
-
- self.previewLayer.frame = frame;
-
- // if (self.previewLayer.connection.isVideoOrientationSupported) {
- // self.previewLayer.connection.videoOrientation = [self captureVideoOrientation];
- // }
- //
- // if ([self.captureOutput connectionWithMediaType:AVMediaTypeVideo].isVideoOrientationSupported) {
- // [self.captureOutput connectionWithMediaType:AVMediaTypeVideo].videoOrientation = [self captureVideoOrientation];
- // }
- //
- }
- - (BOOL)camerAuthorization {
-
- AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
- if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) {
- return NO;
- }
- return YES;
- }
- - (void)initCapture {
-
-
-
- self.cameraInitial = NO;
-
- if (![self camerAuthorization]) {
-
- NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
- NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
- if (!appName) {
- appName = [infoDict objectForKey:@"CFBundleName"];
- }
- __weak typeof(self) weakSelf = self;
- UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Warning" message:[NSString stringWithFormat:@"Camera access denied, please change %@ setting, allow App use camera. (setting -> privacy -> camera enable %@)",[UIDevice currentDevice].model,appName] preferredStyle:UIAlertControllerStyleAlert];
- UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
- [weakSelf dismissViewControllerAnimated:YES completion:nil];
- }];
- [alert addAction:action];
- [self presentViewController:alert animated:YES completion:nil];
-
- return;
- }
-
- self.captureSession = [[AVCaptureSession alloc] init];
-
- self.captureDevice = [self videoDevicePosition:AVCaptureDevicePositionBack];
- if (!self.captureDevice) {
- NSLog(@"there is no capture device while init camera");
- return;
- }
-
- NSError *error;
- self.captureInput = [[AVCaptureDeviceInput alloc] initWithDevice:self.captureDevice error:&error];
-
- if (error) {
- NSLog(@"init camera error: %@",error);
- return;
- }
-
- [self.captureSession beginConfiguration];
-
- if ([_captureSession canSetSessionPreset:AVCaptureSessionPresetPhoto]) {
- _captureSession.sessionPreset = AVCaptureSessionPresetPhoto;
- }
-
- // if ([self.captureDevice isFlashAvailable] && [_captureDevice isFlashModeSupported:AVCaptureFlashModeAuto]) {
- if ([self.captureDevice isFlashAvailable] && [self.photoOutput supportedFlashModes]) {
- NSError *configErr;
- [self.captureDevice lockForConfiguration:&configErr];
- // AVCapturePhotoSettings.flashMode
- // [self.captureDevice setFlashMode:AVCaptureFlashModeAuto];
- [self.captureDevice unlockForConfiguration];
- }
-
- // if ([self.captureDevice isAdjustingWhiteBalance] && [self.captureDevice isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
- // NSError *configErr;
- // [self.captureDevice lockForConfiguration:&configErr];
- // [self.captureDevice setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
- // [self.captureDevice unlockForConfiguration];
- // }
-
- if ([self.captureSession canAddInput:self.captureInput]) {
-
-
- [self.captureSession addInput:self.captureInput];
-
- // if ([self.captureSession canSetSessionPreset:AVCaptureSessionPreset1920x1080]) {
- // self.captureSession.sessionPreset = AVCaptureSessionPreset1920x1080;
- // } else {
- // if ([self.captureSession canSetSessionPreset:AVCaptureSessionPresetHigh]) {
- // self.captureSession.sessionPreset = AVCaptureSessionPresetHigh;
- // }
- // }
-
- } else {
- NSLog(@"init camera can't add input");
- return;
- }
-
- [self.captureSession commitConfiguration];
-
- self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
- self.previewLayer.videoGravity = self.gravity;
- [self.previewContainer.layer addSublayer:self.previewLayer];
-
- self.cameraInitial = YES;
- }
- - (void)initTakePicture {
- if (!self.cameraInitial) {
- return;
- }
- // self.captureOutput = [[AVCaptureStillImageOutput alloc] init];
- self.photoOutput = [AVCapturePhotoOutput new];
-
- // NSDictionary *setting = @{AVVideoCodecKey:AVVideoCodecJPEG};
- // AVVideoCodecTypeJPEG
- // self.photoSetting.cod
- // [self.captureOutput setOutputSettings:setting];
- //
- if ([self.captureSession canAddOutput:self.photoOutput]) {
- [self.captureSession addOutput:self.photoOutput];
- }
-
- // AVCaptureConnection *connection = [self.captureOutput connectionWithMediaType:AVMediaTypeVideo];
- // if (connection.isVideoOrientationSupported) { // addOutput之后判断,否则一直都是false
- // connection.videoOrientation = [self captureVideoOrientation];
- // }
-
- }
- - (AVCaptureDevice *) videoDevicePosition:(AVCaptureDevicePosition)position {
- // NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
-
-
- AVCaptureDeviceDiscoverySession * _Nonnull cameras = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera] mediaType:AVMediaTypeVideo position: AVCaptureDevicePositionUnspecified];//AVCaptureDevicePositionFront & AVCaptureDevicePositionBack
- // //获取当前摄像头方向
- // AVCaptureDevicePosition currentPosition = self.captureDeviceInput.device.position;
- // AVCaptureDevicePosition toPosition = AVCaptureDevicePositionUnspecified;
- // if (currentPosition == AVCaptureDevicePositionBack || currentPosition == AVCaptureDevicePositionUnspecified) {
- // toPosition = AVCaptureDevicePositionFront;
- // }else{
- // toPosition = AVCaptureDevicePositionBack;
- // }
-
-
- // NSArray* captureDeviceArray = [cameras.devices filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"position == %d",toPosition]];
- // if (captureDeviceArray.count == 0) {
- // return [self throw_errorWithDomain:@"VideoCapture: reverseCamera failed! get new camera failed!"];
- // }
-
- for (AVCaptureDevice *device in cameras.devices) {
- if ([device position] == position) {
- return device;
- }
- }
-
- return nil;
- }
- - (AVCaptureVideoOrientation)captureVideoOrientation {
- AVCaptureVideoOrientation result;
-
- // UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
- switch (self.orientationLast) {
- case UIDeviceOrientationPortrait:
- case UIDeviceOrientationFaceUp:
- case UIDeviceOrientationFaceDown:
- result = AVCaptureVideoOrientationPortrait;
- break;
- case UIDeviceOrientationPortraitUpsideDown:
- //如果这里设置成AVCaptureVideoOrientationPortraitUpsideDown,则视频方向和拍摄时的方向是相反的。
- result = AVCaptureVideoOrientationPortraitUpsideDown;
- break;
- case UIDeviceOrientationLandscapeLeft:
- result = AVCaptureVideoOrientationLandscapeRight;
- break;
- case UIDeviceOrientationLandscapeRight:
- result = AVCaptureVideoOrientationLandscapeLeft;
- break;
- default:
- result = AVCaptureVideoOrientationPortrait;
- break;
- }
-
- return result;
- }
- #pragma mark - Action
- - (IBAction)takePictureBtnClick:(UIButton *)sender {
-
- // UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
- // NSLog(@"UIDeviceOrientation %ld",deviceOrientation);
- // [self.captureOutput connectionWithMediaType:AVMediaTypeVideo];
- if (!self.cameraInitial) {
- return;
- }
- sender.enabled = false;
- // AVCaptureConnection *connection = [self.captureOutput connectionWithMediaType:AVMediaTypeVideo];
- //
- // if (connection.isVideoOrientationSupported) { // addOutput之后判断,否则一直都是false
- // connection.videoOrientation = [self captureVideoOrientation];
- // }
- //
- // NSLog(@"capture orientation %ld",connection.videoOrientation);
- ;
- // __weak typeof(self) weakSelf = self;
- self.photoSetting= [AVCapturePhotoSettings photoSettings];
- if(self.captureDevice.hasFlash)
- {
-
- self.photoSetting.flashMode =AVCaptureFlashModeAuto;
- }
- [self.photoOutput capturePhotoWithSettings:self.photoSetting delegate:self];
- }
- - (IBAction)returnButtonClick:(UIButton *)sender {
- if (self.navigationController) {
- [self.navigationController popViewControllerAnimated:YES];
- } else {
- [self dismissViewControllerAnimated:YES completion:nil];
- }
-
- if (self.navigationController) {
- [self.navigationController setNavigationBarHidden:self.barHidden animated:YES];
- }
- }
- #pragma mark - Utils
- + (UIImage *)imageWithColor:(UIColor *)color Size:(CGSize)size {
-
- UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
- CGContextRef ctx = UIGraphicsGetCurrentContext();
- CGContextAddEllipseInRect(ctx, CGRectMake(5, 5, size.width - 10, size.height - 10));
- CGContextSetFillColorWithColor(ctx, color.CGColor);
- CGContextSetStrokeColorWithColor(ctx, [UIColor whiteColor].CGColor);
- CGContextSetLineWidth(ctx, 3.0f);
- CGContextDrawPath(ctx, kCGPathFillStroke);
- UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
-
- return img;
- }
- #pragma mark - AVCapturePhotoCaptureDelegate
- -(void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error API_AVAILABLE(ios(11.0)) {
- if (!error) {
- // 使用该方式获取图片,可能图片会存在旋转问题,在使用的时候调整图片即可
- NSData *imageData = [photo fileDataRepresentation];
- UIImage *image = [UIImage imageWithData:imageData];
-
- // NSData *imageData=[AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
- // UIImage *image=[UIImage imageWithData:imageData];
-
- RATakePhotoPreviewController *preVC = [RATakePhotoPreviewController viewControllerFromStoryboard];
- preVC.photoHandler = ^(UIImage *img){
- if (self.completion) {
- self.completion(img);
- }
- };
- preVC.preImage = image;
- if (self.takeMode == RACameraTakeModeTakeOnce) {
- preVC.popTo = self.fromVC;
- preVC.barHidden = self.barHidden;
- }
- [self.navigationController pushViewController:preVC animated:YES];
-
- } else {
- NSLog(@"take picture failed: %@",error);
- }
- // sender.enabled = true;
- self.takePhotoBtn.enabled = true;
-
-
-
- }
- @end
|