RACameraViewController.m 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. }
  41. - (void)didReceiveMemoryWarning {
  42. [super didReceiveMemoryWarning];
  43. // Dispose of any resources that can be recreated.
  44. }
  45. - (void)viewWillAppear:(BOOL)animated {
  46. [super viewWillAppear:animated];
  47. if (self.cameraInitial) {
  48. [self.captureSession startRunning];
  49. }
  50. }
  51. - (void)viewWillDisappear:(BOOL)animated {
  52. [super viewWillDisappear:animated];
  53. if ([self.captureSession isRunning]) {
  54. [self.captureSession stopRunning];
  55. }
  56. }
  57. - (void)viewDidLayoutSubviews {
  58. [super viewDidLayoutSubviews];
  59. self.previewLayer.frame = self.previewContainer.bounds;
  60. if (self.previewLayer.connection.isVideoOrientationSupported) {
  61. self.previewLayer.connection.videoOrientation = [self captureVideoOrientation];
  62. }
  63. if ([self.captureOutput connectionWithMediaType:AVMediaTypeVideo].isVideoOrientationSupported) {
  64. [self.captureOutput connectionWithMediaType:AVMediaTypeVideo].videoOrientation = [self captureVideoOrientation];
  65. }
  66. }
  67. #pragma mark - Capture
  68. - (BOOL)camerAuthorization {
  69. AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  70. if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) {
  71. return NO;
  72. }
  73. return YES;
  74. }
  75. - (void)initCapture {
  76. self.cameraInitial = NO;
  77. if (![self camerAuthorization]) {
  78. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  79. NSString *appName = [infoDict objectForKey:@"CFBundleName"];
  80. __weak typeof(self) weakSelf = self;
  81. 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];
  82. UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  83. [weakSelf dismissViewControllerAnimated:YES completion:nil];
  84. }];
  85. [alert addAction:action];
  86. [self presentViewController:alert animated:YES completion:nil];
  87. return;
  88. }
  89. self.captureSession = [[AVCaptureSession alloc] init];
  90. self.captureDevice = [self videoDevicePosition:AVCaptureDevicePositionBack];
  91. if (!self.captureDevice) {
  92. NSLog(@"there is no capture device while init camera");
  93. return;
  94. }
  95. NSError *error;
  96. self.captureInput = [[AVCaptureDeviceInput alloc] initWithDevice:self.captureDevice error:&error];
  97. if (error) {
  98. NSLog(@"init camera error: %@",error);
  99. return;
  100. }
  101. [self.captureSession beginConfiguration];
  102. if ([_captureSession canSetSessionPreset:AVCaptureSessionPresetHigh]) {
  103. _captureSession.sessionPreset = AVCaptureSessionPresetHigh;
  104. }
  105. if ([self.captureSession canAddInput:self.captureInput]) {
  106. [self.captureSession addInput:self.captureInput];
  107. // if ([self.captureSession canSetSessionPreset:AVCaptureSessionPreset1920x1080]) {
  108. // self.captureSession.sessionPreset = AVCaptureSessionPreset1920x1080;
  109. // } else {
  110. // if ([self.captureSession canSetSessionPreset:AVCaptureSessionPresetHigh]) {
  111. // self.captureSession.sessionPreset = AVCaptureSessionPresetHigh;
  112. // }
  113. // }
  114. } else {
  115. NSLog(@"init camera can't add input");
  116. return;
  117. }
  118. [self.captureSession commitConfiguration];
  119. self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
  120. self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  121. [self.previewContainer.layer addSublayer:self.previewLayer];
  122. self.cameraInitial = YES;
  123. }
  124. - (void)initTakePicture {
  125. if (!self.cameraInitial) {
  126. return;
  127. }
  128. self.captureOutput = [[AVCaptureStillImageOutput alloc] init];
  129. NSDictionary *setting = @{AVVideoCodecKey:AVVideoCodecJPEG};
  130. [self.captureOutput setOutputSettings:setting];
  131. if ([self.captureSession canAddOutput:self.captureOutput]) {
  132. [self.captureSession addOutput:self.captureOutput];
  133. }
  134. AVCaptureConnection *connection = [self.captureOutput connectionWithMediaType:AVMediaTypeVideo];
  135. if (connection.isVideoOrientationSupported) { // addOutput之后判断,否则一直都是false
  136. connection.videoOrientation = [self captureVideoOrientation];
  137. }
  138. }
  139. - (AVCaptureDevice *) videoDevicePosition:(AVCaptureDevicePosition)position {
  140. NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  141. for (AVCaptureDevice *device in videoDevices) {
  142. if ([device position] == position) {
  143. return device;
  144. }
  145. }
  146. return nil;
  147. }
  148. - (AVCaptureVideoOrientation)captureVideoOrientation {
  149. AVCaptureVideoOrientation result;
  150. UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
  151. switch (deviceOrientation) {
  152. case UIDeviceOrientationPortrait:
  153. case UIDeviceOrientationFaceUp:
  154. case UIDeviceOrientationFaceDown:
  155. result = AVCaptureVideoOrientationPortrait;
  156. break;
  157. case UIDeviceOrientationPortraitUpsideDown:
  158. //如果这里设置成AVCaptureVideoOrientationPortraitUpsideDown,则视频方向和拍摄时的方向是相反的。
  159. result = AVCaptureVideoOrientationPortrait;
  160. break;
  161. case UIDeviceOrientationLandscapeLeft:
  162. result = AVCaptureVideoOrientationLandscapeRight;
  163. break;
  164. case UIDeviceOrientationLandscapeRight:
  165. result = AVCaptureVideoOrientationLandscapeLeft;
  166. break;
  167. default:
  168. result = AVCaptureVideoOrientationPortrait;
  169. break;
  170. }
  171. return result;
  172. }
  173. #pragma mark - Action
  174. - (IBAction)takePictureBtnClick:(UIButton *)sender {
  175. if (!self.cameraInitial) {
  176. return;
  177. }
  178. AVCaptureConnection *connection = [self.captureOutput connectionWithMediaType:AVMediaTypeVideo];
  179. [self.captureOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:^(CMSampleBufferRef _Nullable imageDataSampleBuffer, NSError * _Nullable error) {
  180. if (imageDataSampleBuffer) {
  181. NSData *imageData=[AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
  182. UIImage *image=[UIImage imageWithData:imageData];
  183. __weak typeof(self) weakSelf = self;
  184. RATakePhotoPreviewController *preVC = [RATakePhotoPreviewController viewControllerFromStoryboard];
  185. preVC.photoHandler = ^(UIImage *img){
  186. if (weakSelf) {
  187. __strong typeof(weakSelf) strongSelf = weakSelf;
  188. if (strongSelf.completion) {
  189. strongSelf.completion(img);
  190. }
  191. }
  192. };
  193. preVC.preImage = image;
  194. preVC.popTo = self.fromVC;
  195. [self.navigationController pushViewController:preVC animated:YES];
  196. } else {
  197. NSLog(@"take picture failed: %@",error);
  198. }
  199. }];
  200. }
  201. #pragma mark - Utils
  202. + (UIImage *)imageWithColor:(UIColor *)color Size:(CGSize)size {
  203. UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
  204. CGContextRef ctx = UIGraphicsGetCurrentContext();
  205. CGContextAddEllipseInRect(ctx, CGRectMake(5, 5, size.width - 10, size.height - 10));
  206. CGContextSetFillColorWithColor(ctx, color.CGColor);
  207. CGContextSetStrokeColorWithColor(ctx, [UIColor whiteColor].CGColor);
  208. CGContextSetLineWidth(ctx, 3.0f);
  209. CGContextDrawPath(ctx, kCGPathFillStroke);
  210. UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
  211. UIGraphicsEndImageContext();
  212. return img;
  213. }
  214. @end