RAQRCodeScannerViewController.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. //
  2. // RAQRCodeScannerViewController.m
  3. // Apex And Drivers
  4. //
  5. // Created by Jack on 2018/6/5.
  6. // Copyright © 2018年 USAI. All rights reserved.
  7. //
  8. #import "RAQRCodeScannerViewController.h"
  9. #import <AVKit/AVKit.h>
  10. @interface RAQRCodeScannerViewController () <AVCaptureMetadataOutputObjectsDelegate>
  11. @property (strong, nonatomic) IBOutlet UIView *scanerView;
  12. @property (nonatomic,strong) IBOutlet UIView *previewContainer;
  13. @property (strong, nonatomic) IBOutlet UIView *maskView;
  14. @property (strong, nonatomic) IBOutlet UIButton *scanBtn;
  15. @property (strong, nonatomic) IBOutlet UIButton *backBtn;
  16. @property (nonatomic,strong) AVCaptureDevice *device;
  17. @property (nonatomic,strong) AVCaptureDeviceInput *input;
  18. @property (nonatomic,strong) AVCaptureMetadataOutput *output;
  19. @property (nonatomic,strong) AVCaptureSession *session;
  20. @property (nonatomic,strong) AVCaptureVideoPreviewLayer *previewLayer;
  21. @property (nonatomic,assign) BOOL scannerEnable;
  22. @property (nonatomic,assign) BOOL scannerInitial;
  23. @property (nonatomic,strong) CAGradientLayer *scanLineLayer;
  24. @property (nonatomic,strong) CAShapeLayer *maskLayer;
  25. @property (nonatomic,strong) CAShapeLayer *rectLayer;
  26. @property (nonatomic,assign) BOOL navigationBarStatus;
  27. @property (weak, nonatomic) IBOutlet UITextView *tvdbg_log;
  28. @end
  29. @implementation RAQRCodeScannerViewController
  30. + (NSString *)storyboardID {
  31. return NSStringFromClass([self class]);
  32. }
  33. + (instancetype)viewControllerFromStoryboard {
  34. RAQRCodeScannerViewController *scannerVC = [[UIStoryboard storyboardWithName:@"QRCode" bundle:nil] instantiateViewControllerWithIdentifier:[self storyboardID]];
  35. return scannerVC;
  36. }
  37. - (void)viewDidLoad {
  38. [super viewDidLoad];
  39. self.tvdbg_log.hidden = true;
  40. // Do any additional setup after loading the view.
  41. if (self.navigationController) {
  42. self.navigationBarStatus = self.navigationController.navigationBarHidden;
  43. [self.navigationController setNavigationBarHidden:YES animated:NO];
  44. }
  45. self.scanerView.layer.borderColor = [UIColor blackColor].CGColor;
  46. self.scanerView.layer.borderWidth = 0.5f;
  47. UIImage *normal_img = [self.class imageWithColor:[UIColor redColor] Size:CGSizeMake(60, 60)];
  48. UIImage *highlight_img = [self.class imageWithColor:[UIColor greenColor] Size:CGSizeMake(60, 60)];
  49. [self.scanBtn setImage:normal_img forState:UIControlStateNormal];
  50. [self.scanBtn setImage:highlight_img forState:UIControlStateHighlighted];
  51. if ([self camerAuthorization]) {
  52. [self initCapture];
  53. } else {
  54. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
  55. dispatch_async(dispatch_get_main_queue(), ^{
  56. if (granted) {
  57. [self initCapture];
  58. [self resetPreview];
  59. if (![self.session isRunning]) {
  60. [self.session startRunning];
  61. }
  62. } else {
  63. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  64. NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
  65. if (!appName) {
  66. appName = [infoDict objectForKey:@"CFBundleName"];
  67. }
  68. __weak typeof(self) weakSelf = self;
  69. 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];
  70. UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  71. [weakSelf didCancel];
  72. }];
  73. [alert addAction:action];
  74. [self presentViewController:alert animated:YES completion:nil];
  75. }
  76. });
  77. }];
  78. }
  79. }
  80. //- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
  81. // return UIInterfaceOrientationPortrait;
  82. //}
  83. - (AVCaptureVideoOrientation)captureVideoOrientation {
  84. AVCaptureVideoOrientation result;
  85. UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
  86. switch (deviceOrientation) {
  87. case UIDeviceOrientationPortrait:
  88. case UIDeviceOrientationFaceUp:
  89. case UIDeviceOrientationFaceDown:
  90. result = AVCaptureVideoOrientationPortrait;
  91. break;
  92. case UIDeviceOrientationPortraitUpsideDown:
  93. //如果这里设置成AVCaptureVideoOrientationPortraitUpsideDown,则视频方向和拍摄时的方向是相反的。
  94. result = AVCaptureVideoOrientationPortrait;
  95. break;
  96. case UIDeviceOrientationLandscapeLeft:
  97. result = AVCaptureVideoOrientationLandscapeRight;
  98. break;
  99. case UIDeviceOrientationLandscapeRight:
  100. result = AVCaptureVideoOrientationLandscapeLeft;
  101. break;
  102. default:
  103. result = AVCaptureVideoOrientationPortrait;
  104. break;
  105. }
  106. return result;
  107. }
  108. - (void)viewDidLayoutSubviews {
  109. [super viewDidLayoutSubviews];
  110. [self resetPreview];
  111. }
  112. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
  113. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  114. // NSLog(@"device orientation: %ld & statusbar orientaion: %ld",[UIDevice currentDevice].orientation,[UIApplication sharedApplication].statusBarOrientation);
  115. }
  116. - (void)viewWillAppear:(BOOL)animated {
  117. [super viewWillAppear:animated];
  118. if (self.scannerInitial) {
  119. [self.session startRunning];
  120. }
  121. }
  122. - (void)viewWillDisappear:(BOOL)animated {
  123. [super viewWillDisappear:animated];
  124. if ([self.session isRunning]) {
  125. [self.session stopRunning];
  126. }
  127. }
  128. - (void)didReceiveMemoryWarning {
  129. [super didReceiveMemoryWarning];
  130. // Dispose of any resources that can be recreated.
  131. }
  132. - (void)resetPreview {
  133. self.previewLayer.frame = self.previewContainer.bounds;
  134. AVCaptureVideoOrientation orientation = [self captureVideoOrientation];
  135. if (self.previewLayer.connection.isVideoOrientationSupported) {
  136. self.previewLayer.connection.videoOrientation = orientation;
  137. }
  138. CGFloat w = CGRectGetWidth(self.previewContainer.bounds);
  139. CGFloat h = CGRectGetHeight(self.previewContainer.bounds);
  140. /**
  141. rectOfInterest
  142. 竖屏 x轴和y轴要交换一下
  143. Left、Right:Home键反方向X为0
  144. */
  145. CGRect rect = CGRectMake(CGRectGetMinY(self.scanerView.frame) / h, CGRectGetMinX(self.scanerView.frame) / w, CGRectGetHeight(self.scanerView.frame) / h, CGRectGetWidth(self.scanerView.frame) / w);
  146. if (orientation == AVCaptureVideoOrientationLandscapeRight) {
  147. rect = CGRectMake(CGRectGetMinX(self.scanerView.frame) / w, CGRectGetMinY(self.scanerView.frame) / h, CGRectGetWidth(self.scanerView.frame) / w,CGRectGetHeight(self.scanerView.frame) / h);
  148. } else if (orientation == AVCaptureVideoOrientationLandscapeLeft){
  149. rect = CGRectMake(1 - CGRectGetMaxX(self.scanerView.frame) / w, 1 - CGRectGetMaxY(self.scanerView.frame) / h, CGRectGetWidth(self.scanerView.frame) / w,CGRectGetHeight(self.scanerView.frame) / h);
  150. } else {
  151. rect = CGRectMake(CGRectGetMinY(self.scanerView.frame) / h, CGRectGetMinX(self.scanerView.frame) / w, CGRectGetHeight(self.scanerView.frame) / h, CGRectGetWidth(self.scanerView.frame) / w);
  152. }
  153. [self.output setRectOfInterest:rect];
  154. [self.view bringSubviewToFront:self.scanerView];
  155. CGRect scanlineFrame = CGRectMake(0, CGRectGetMidY(self.scanerView.bounds) - 0.5, CGRectGetWidth(self.scanerView.bounds), 1);
  156. self.scanLineLayer.frame = scanlineFrame;
  157. [self.scanerView.layer insertSublayer:self.scanLineLayer atIndex:0];
  158. UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.maskView.bounds];
  159. UIBezierPath *subPath = [UIBezierPath bezierPathWithRect:self.scanerView.frame];
  160. [path appendPath:subPath];
  161. if (!self.maskLayer) {
  162. self.maskLayer = [CAShapeLayer layer];
  163. self.maskLayer.fillColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.5].CGColor;
  164. self.maskLayer.fillRule = kCAFillRuleEvenOdd;
  165. }
  166. self.maskLayer.path = path.CGPath;
  167. if (!self.rectLayer) {
  168. self.rectLayer = [CAShapeLayer layer];
  169. self.rectLayer.fillColor = [UIColor clearColor].CGColor;
  170. self.rectLayer.strokeColor = [UIColor whiteColor].CGColor;
  171. self.rectLayer.lineWidth = 0.5f;
  172. }
  173. self.rectLayer.path = subPath.CGPath;
  174. [self.maskLayer addSublayer:self.rectLayer];
  175. [self.maskView.layer addSublayer:self.maskLayer];
  176. }
  177. - (CAGradientLayer *)scanLineLayer {
  178. if (!_scanLineLayer) {
  179. CAGradientLayer *gradientLayer = [CAGradientLayer layer];
  180. //set gradient colors
  181. // 数组成员接受 CGColorRef 类型的值
  182. gradientLayer.colors = @[(__bridge id)[UIColor colorWithRed:1 green:0 blue:0 alpha:0.2].CGColor,(__bridge id)[UIColor redColor].CGColor,(__bridge id)[UIColor colorWithRed:1 green:0 blue:0 alpha:0.2].CGColor];
  183. gradientLayer.locations = @[@2.5,@0.5,@0.75];
  184. gradientLayer.startPoint = CGPointMake(0, 0);
  185. gradientLayer.endPoint = CGPointMake(1, 0);
  186. _scanLineLayer = gradientLayer;
  187. }
  188. return _scanLineLayer;
  189. }
  190. #pragma mark - Private
  191. - (void)didCancel {
  192. if (self.QRCodeViewControllerDidCanceled) {
  193. self.QRCodeViewControllerDidCanceled(self);
  194. if (self.navigationController) {
  195. [self.navigationController setNavigationBarHidden:self.navigationBarStatus animated:NO];
  196. }
  197. }
  198. }
  199. #pragma mark - Init
  200. - (void)initCapture {
  201. self.scannerInitial = NO;
  202. if (![self camerAuthorization]) {
  203. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  204. NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
  205. if (!appName) {
  206. appName = [infoDict objectForKey:@"CFBundleName"];
  207. }
  208. __weak typeof(self) weakSelf = self;
  209. 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];
  210. UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  211. [weakSelf didCancel];
  212. }];
  213. [alert addAction:action];
  214. [self presentViewController:alert animated:YES completion:nil];
  215. return;
  216. }
  217. self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  218. NSError *inputError;
  219. self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&inputError];
  220. if (inputError) {
  221. NSLog(@"init scanner input error: %@",inputError);
  222. return;
  223. }
  224. self.session = [[AVCaptureSession alloc] init];
  225. [self.session setSessionPreset:AVCaptureSessionPresetHigh];
  226. if ([self.session canAddInput:self.input]) {
  227. [self.session addInput:self.input];
  228. } else {
  229. NSLog(@"init scanner can't add input");
  230. return;
  231. }
  232. self.output = [[AVCaptureMetadataOutput alloc] init];
  233. [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
  234. if ([self.session canAddOutput:self.output]) {
  235. [self.session addOutput:self.output];
  236. } else {
  237. NSLog(@"init scanner can't add output");
  238. return;
  239. }
  240. NSLog(@"%@", [_output availableMetadataObjectTypes]);
  241. NSString* log = [NSString stringWithFormat:@"%@ \n",[_output availableMetadataObjectTypes]];
  242. self.tvdbg_log.text = [self.tvdbg_log.text stringByAppendingString:log];
  243. if(self.scanType==RAScanTypeAll)
  244. {
  245. self.output.metadataObjectTypes = self.output.availableMetadataObjectTypes;
  246. }
  247. else if(self.scanType == RAScanTypeBarcode)
  248. {
  249. self.output.metadataObjectTypes = @[
  250. // AVMetadataObjectTypeQRCode,
  251. AVMetadataObjectTypeEAN13Code,
  252. AVMetadataObjectTypeEAN8Code,
  253. AVMetadataObjectTypeUPCECode,
  254. AVMetadataObjectTypeCode39Code,
  255. AVMetadataObjectTypeCode39Mod43Code,
  256. AVMetadataObjectTypeCode93Code,
  257. AVMetadataObjectTypeCode128Code
  258. // AVMetadataObjectTypePDF417Code
  259. ];
  260. }
  261. else
  262. {
  263. self.output.metadataObjectTypes = @[
  264. AVMetadataObjectTypeQRCode,
  265. // AVMetadataObjectTypeEAN13Code,
  266. // AVMetadataObjectTypeEAN8Code,
  267. // AVMetadataObjectTypeUPCECode,
  268. // AVMetadataObjectTypeCode39Code,
  269. // AVMetadataObjectTypeCode39Mod43Code,
  270. // AVMetadataObjectTypeCode93Code,
  271. // AVMetadataObjectTypeCode128Code
  272. AVMetadataObjectTypePDF417Code
  273. ];
  274. }
  275. log = [NSString stringWithFormat:@"set : \n %@ \n",self.output.metadataObjectTypes];
  276. self.tvdbg_log.text = [self.tvdbg_log.text stringByAppendingString:log];
  277. self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
  278. self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  279. [self.previewContainer.layer addSublayer:self.previewLayer];
  280. self.scannerInitial = YES;
  281. }
  282. - (BOOL)camerAuthorization {
  283. AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  284. if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) {
  285. return NO;
  286. }
  287. return YES;
  288. }
  289. #pragma mark - AVCaptureMetadataOutputObjectsDelegate
  290. - (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
  291. if (!self.scannerEnable) {
  292. return;
  293. }
  294. NSString* log = [NSString stringWithFormat:@"%@ \n",@"didOutputMetadataObjects"];
  295. self.tvdbg_log.text = [self.tvdbg_log.text stringByAppendingString:log];
  296. if ([metadataObjects count] > 0) {
  297. [self.session stopRunning];
  298. AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects objectAtIndex:0];
  299. log = [NSString stringWithFormat:@"type %@ \n",metadataObject.type];
  300. self.tvdbg_log.text = [self.tvdbg_log.text stringByAppendingString:log];
  301. NSString *codeValue = metadataObject.stringValue;
  302. if (self.QRCodeViewControllerDidCompletion) {
  303. self.QRCodeViewControllerDidCompletion(self, codeValue);
  304. if (self.navigationController) {
  305. [self.navigationController setNavigationBarHidden:self.navigationBarStatus animated:NO];
  306. }
  307. }
  308. }
  309. }
  310. #pragma mark - Action
  311. - (IBAction)scannerBtnTouchDown:(UIButton *)sender {
  312. self.scannerEnable = YES;
  313. }
  314. - (IBAction)scannerBtnTouchUp:(UIButton *)sender {
  315. self.scannerEnable = NO;
  316. }
  317. - (IBAction)scannerBtnTouchUpOutSide:(UIButton *)sender {
  318. self.scannerEnable = NO;
  319. }
  320. - (IBAction)scannerBtnTouchCancel:(UIButton *)sender {
  321. self.scannerEnable = NO;
  322. }
  323. - (IBAction)backBtnClick:(UIButton *)sender {
  324. [self didCancel];
  325. }
  326. #pragma mark - Utils
  327. + (UIImage *)imageWithColor:(UIColor *)color Size:(CGSize)size {
  328. UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
  329. CGContextRef ctx = UIGraphicsGetCurrentContext();
  330. CGContextAddEllipseInRect(ctx, CGRectMake(5, 5, size.width - 10, size.height - 10));
  331. CGContextSetFillColorWithColor(ctx, color.CGColor);
  332. CGContextSetStrokeColorWithColor(ctx, [UIColor whiteColor].CGColor);
  333. CGContextSetLineWidth(ctx, 3.0f);
  334. CGContextDrawPath(ctx, kCGPathFillStroke);
  335. UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
  336. UIGraphicsEndImageContext();
  337. return img;
  338. }
  339. @end