RACameraViewController.m 14 KB

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