RACameraViewController.m 14 KB

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