RACameraViewController.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. //
  2. // RACameraViewController.m
  3. // Apex And Drivers
  4. //
  5. // Created by Jack on 2018/6/5.
  6. // Copyright © 2018年 USAI. All rights reserved.
  7. //
  8. #import "RACameraViewController.h"
  9. #import <AVFoundation/AVFoundation.h>
  10. #import "RATakePhotoPreviewController.h"
  11. @interface RACameraViewController ()
  12. @property (nonatomic,strong) IBOutlet UIView *previewContainer;
  13. @property (nonatomic,strong) IBOutlet UIView *controlContanier;
  14. @property (strong, nonatomic) IBOutlet UIButton *takePhotoBtn;
  15. @property (nonatomic,assign) BOOL barHidden;
  16. #pragma mark - Camera
  17. @property (nonatomic,strong) AVCaptureDevice *captureDevice;
  18. @property (nonatomic,strong) AVCaptureSession *captureSession;
  19. @property (nonatomic,strong) AVCaptureDeviceInput *captureInput;
  20. @property (nonatomic,strong) AVCaptureStillImageOutput *captureOutput;
  21. @property (nonatomic,strong) AVCaptureVideoPreviewLayer *previewLayer;
  22. @property (nonatomic,assign) BOOL cameraInitial;
  23. @end
  24. @implementation RACameraViewController
  25. + (NSString *)storyboardID {
  26. return NSStringFromClass([self class]);
  27. }
  28. + (instancetype)viewControllerFromStoryboard {
  29. RACameraViewController *cameraVC = [[UIStoryboard storyboardWithName:@"Camera" bundle:nil] instantiateViewControllerWithIdentifier:[self storyboardID]];
  30. return cameraVC;
  31. }
  32. - (void)viewDidLoad {
  33. [super viewDidLoad];
  34. // Do any additional setup after loading the view.
  35. UIImage *normal_img = [self.class imageWithColor:[UIColor redColor] Size:CGSizeMake(60, 60)];
  36. UIImage *highlight_img = [self.class imageWithColor:[UIColor whiteColor] Size:CGSizeMake(60, 60)];
  37. [self.takePhotoBtn setImage:normal_img forState:UIControlStateNormal];
  38. [self.takePhotoBtn setImage:highlight_img forState:UIControlStateHighlighted];
  39. // [self initCapture];
  40. // [self initTakePicture];
  41. if ([self camerAuthorization]) {
  42. [self initCapture];
  43. [self initTakePicture];
  44. } else {
  45. // fix:第一次打开相机的时候授权成功后,未初始化相机
  46. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
  47. dispatch_async(dispatch_get_main_queue(), ^{
  48. if (granted) {
  49. [self initCapture];
  50. [self initTakePicture];
  51. CGRect frame = self.previewContainer.bounds;
  52. [self resetPreview:CGRectOffset(frame, CGRectGetWidth(frame), 0)];
  53. [UIView animateWithDuration:0.3 animations:^{
  54. self.previewLayer.frame = frame;
  55. }];
  56. if (self.cameraInitial && !self.captureSession.isRunning) {
  57. [self.captureSession startRunning];
  58. }
  59. } else {
  60. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  61. NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
  62. __weak typeof(self) weakSelf = self;
  63. 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];
  64. UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  65. [weakSelf dismissViewControllerAnimated:YES completion:nil];
  66. }];
  67. [alert addAction:action];
  68. [self presentViewController:alert animated:YES completion:nil];
  69. }
  70. });
  71. }];
  72. }
  73. /**
  74. * 管理导航条
  75. * 在viewDidload的时候隐藏导航条
  76. * 恢复导航条的显示/隐藏有两个地方:1.退出的时候;2.确认使用照片的时候
  77. */
  78. if (self.navigationController) {
  79. BOOL navBarHidden = self.navigationController.navigationBar.hidden;
  80. self.barHidden = navBarHidden;
  81. if (!navBarHidden) {
  82. [self.navigationController setNavigationBarHidden:YES animated:YES];
  83. }
  84. }
  85. }
  86. - (void)didReceiveMemoryWarning {
  87. [super didReceiveMemoryWarning];
  88. // Dispose of any resources that can be recreated.
  89. }
  90. - (void)viewWillAppear:(BOOL)animated {
  91. [super viewWillAppear:animated];
  92. if (self.cameraInitial && !self.captureSession.isRunning) {
  93. [self.captureSession startRunning];
  94. }
  95. }
  96. - (void)viewWillDisappear:(BOOL)animated {
  97. [super viewWillDisappear:animated];
  98. if ([self.captureSession isRunning]) {
  99. [self.captureSession stopRunning];
  100. }
  101. }
  102. - (BOOL)prefersStatusBarHidden {
  103. return YES;
  104. }
  105. - (void)viewDidLayoutSubviews {
  106. [super viewDidLayoutSubviews];
  107. if ([self camerAuthorization] && self.cameraInitial) {
  108. [self resetPreview:self.previewContainer.bounds];
  109. }
  110. }
  111. #pragma mark - Capture
  112. - (void)resetPreview:(CGRect)frame {
  113. self.previewLayer.frame = frame;
  114. if (self.previewLayer.connection.isVideoOrientationSupported) {
  115. self.previewLayer.connection.videoOrientation = [self captureVideoOrientation];
  116. }
  117. if ([self.captureOutput connectionWithMediaType:AVMediaTypeVideo].isVideoOrientationSupported) {
  118. [self.captureOutput connectionWithMediaType:AVMediaTypeVideo].videoOrientation = [self captureVideoOrientation];
  119. }
  120. }
  121. - (BOOL)camerAuthorization {
  122. AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  123. if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) {
  124. return NO;
  125. }
  126. return YES;
  127. }
  128. - (void)initCapture {
  129. self.cameraInitial = NO;
  130. if (![self camerAuthorization]) {
  131. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  132. NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
  133. __weak typeof(self) weakSelf = self;
  134. 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];
  135. UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  136. [weakSelf dismissViewControllerAnimated:YES completion:nil];
  137. }];
  138. [alert addAction:action];
  139. [self presentViewController:alert animated:YES completion:nil];
  140. return;
  141. }
  142. self.captureSession = [[AVCaptureSession alloc] init];
  143. self.captureDevice = [self videoDevicePosition:AVCaptureDevicePositionBack];
  144. if (!self.captureDevice) {
  145. NSLog(@"there is no capture device while init camera");
  146. return;
  147. }
  148. NSError *error;
  149. self.captureInput = [[AVCaptureDeviceInput alloc] initWithDevice:self.captureDevice error:&error];
  150. if (error) {
  151. NSLog(@"init camera error: %@",error);
  152. return;
  153. }
  154. [self.captureSession beginConfiguration];
  155. if ([_captureSession canSetSessionPreset:AVCaptureSessionPresetHigh]) {
  156. _captureSession.sessionPreset = AVCaptureSessionPresetHigh;
  157. }
  158. if ([self.captureDevice isFlashAvailable] && [_captureDevice isFlashModeSupported:AVCaptureFlashModeAuto]) {
  159. NSError *configErr;
  160. [self.captureDevice lockForConfiguration:&configErr];
  161. [self.captureDevice setFlashMode:AVCaptureFlashModeAuto];
  162. [self.captureDevice unlockForConfiguration];
  163. }
  164. if ([self.captureSession canAddInput:self.captureInput]) {
  165. [self.captureSession addInput:self.captureInput];
  166. // if ([self.captureSession canSetSessionPreset:AVCaptureSessionPreset1920x1080]) {
  167. // self.captureSession.sessionPreset = AVCaptureSessionPreset1920x1080;
  168. // } else {
  169. // if ([self.captureSession canSetSessionPreset:AVCaptureSessionPresetHigh]) {
  170. // self.captureSession.sessionPreset = AVCaptureSessionPresetHigh;
  171. // }
  172. // }
  173. } else {
  174. NSLog(@"init camera can't add input");
  175. return;
  176. }
  177. [self.captureSession commitConfiguration];
  178. self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
  179. self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  180. [self.previewContainer.layer addSublayer:self.previewLayer];
  181. self.cameraInitial = YES;
  182. }
  183. - (void)initTakePicture {
  184. if (!self.cameraInitial) {
  185. return;
  186. }
  187. self.captureOutput = [[AVCaptureStillImageOutput alloc] init];
  188. NSDictionary *setting = @{AVVideoCodecKey:AVVideoCodecJPEG};
  189. [self.captureOutput setOutputSettings:setting];
  190. if ([self.captureSession canAddOutput:self.captureOutput]) {
  191. [self.captureSession addOutput:self.captureOutput];
  192. }
  193. AVCaptureConnection *connection = [self.captureOutput connectionWithMediaType:AVMediaTypeVideo];
  194. if (connection.isVideoOrientationSupported) { // addOutput之后判断,否则一直都是false
  195. connection.videoOrientation = [self captureVideoOrientation];
  196. }
  197. }
  198. - (AVCaptureDevice *) videoDevicePosition:(AVCaptureDevicePosition)position {
  199. NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  200. for (AVCaptureDevice *device in videoDevices) {
  201. if ([device position] == position) {
  202. return device;
  203. }
  204. }
  205. return nil;
  206. }
  207. - (AVCaptureVideoOrientation)captureVideoOrientation {
  208. AVCaptureVideoOrientation result;
  209. UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
  210. switch (deviceOrientation) {
  211. case UIDeviceOrientationPortrait:
  212. case UIDeviceOrientationFaceUp:
  213. case UIDeviceOrientationFaceDown:
  214. result = AVCaptureVideoOrientationPortrait;
  215. break;
  216. case UIDeviceOrientationPortraitUpsideDown:
  217. //如果这里设置成AVCaptureVideoOrientationPortraitUpsideDown,则视频方向和拍摄时的方向是相反的。
  218. result = AVCaptureVideoOrientationPortrait;
  219. break;
  220. case UIDeviceOrientationLandscapeLeft:
  221. result = AVCaptureVideoOrientationLandscapeRight;
  222. break;
  223. case UIDeviceOrientationLandscapeRight:
  224. result = AVCaptureVideoOrientationLandscapeLeft;
  225. break;
  226. default:
  227. result = AVCaptureVideoOrientationPortrait;
  228. break;
  229. }
  230. return result;
  231. }
  232. #pragma mark - Action
  233. - (IBAction)takePictureBtnClick:(UIButton *)sender {
  234. if (!self.cameraInitial) {
  235. return;
  236. }
  237. AVCaptureConnection *connection = [self.captureOutput connectionWithMediaType:AVMediaTypeVideo];
  238. __weak typeof(self) weakSelf = self;
  239. [self.captureOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:^(CMSampleBufferRef _Nullable imageDataSampleBuffer, NSError * _Nullable error) {
  240. if (imageDataSampleBuffer) {
  241. NSData *imageData=[AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
  242. UIImage *image=[UIImage imageWithData:imageData];
  243. RATakePhotoPreviewController *preVC = [RATakePhotoPreviewController viewControllerFromStoryboard];
  244. preVC.photoHandler = ^(UIImage *img){
  245. if (weakSelf) {
  246. __strong typeof(weakSelf) strongSelf = weakSelf;
  247. if (strongSelf.completion) {
  248. strongSelf.completion(img);
  249. }
  250. }
  251. };
  252. preVC.preImage = image;
  253. preVC.popTo = weakSelf.fromVC;
  254. preVC.barHidden = weakSelf.barHidden;
  255. [weakSelf.navigationController pushViewController:preVC animated:YES];
  256. } else {
  257. NSLog(@"take picture failed: %@",error);
  258. }
  259. }];
  260. }
  261. - (IBAction)returnButtonClick:(UIButton *)sender {
  262. if (self.navigationController) {
  263. [self.navigationController popViewControllerAnimated:YES];
  264. } else {
  265. [self dismissViewControllerAnimated:YES completion:nil];
  266. }
  267. if (self.navigationController) {
  268. [self.navigationController setNavigationBarHidden:self.barHidden animated:YES];
  269. }
  270. }
  271. #pragma mark - Utils
  272. + (UIImage *)imageWithColor:(UIColor *)color Size:(CGSize)size {
  273. UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
  274. CGContextRef ctx = UIGraphicsGetCurrentContext();
  275. CGContextAddEllipseInRect(ctx, CGRectMake(5, 5, size.width - 10, size.height - 10));
  276. CGContextSetFillColorWithColor(ctx, color.CGColor);
  277. CGContextSetStrokeColorWithColor(ctx, [UIColor whiteColor].CGColor);
  278. CGContextSetLineWidth(ctx, 3.0f);
  279. CGContextDrawPath(ctx, kCGPathFillStroke);
  280. UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
  281. UIGraphicsEndImageContext();
  282. return img;
  283. }
  284. @end