RACameraViewController.m 12 KB

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