ScannerViewController.m 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. /*
  2. Copyright 2013 Scott Logic Ltd
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #import "ScannerViewController.h"
  14. @import AVFoundation;
  15. #import <AudioToolbox/AudioToolbox.h>
  16. #import "SCShapeView.h"
  17. #import "ScannerControllerView.h"
  18. //#import "DetailViewController.h"
  19. #import "const.h"
  20. #import "AppDelegate.h"
  21. //#import "MainViewController.h"
  22. //#import "ContactListViewController.h"
  23. //#import "CartUtils.h"
  24. #define SCANNER_TARGET_DETAIL 0
  25. #define SCANNER_TARGET_CART 1
  26. //#import "ScannerControlViewController.h"
  27. @interface ScannerViewController () <AVCaptureMetadataOutputObjectsDelegate> {
  28. AVCaptureVideoPreviewLayer *_previewLayer;
  29. SCShapeView *_boundingBox;
  30. NSTimer *_boxHideTimer;
  31. UILabel *_decodedMessage;
  32. }
  33. @end
  34. @implementation ScannerViewController
  35. //- (UIInterfaceOrientationMask)supportedInterfaceOrientations
  36. //{
  37. // return UIInterfaceOrientationMaskPortrait;
  38. //}
  39. //- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
  40. //{
  41. //
  42. // return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
  43. //
  44. //}
  45. - (BOOL)shouldAutorotate
  46. {
  47. return false;
  48. }
  49. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  50. {
  51. // [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context)
  52. // {
  53. // UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
  54. // // do whatever
  55. // } completion:^(id<UIViewControllerTransitionCoordinatorContext> context)
  56. // {
  57. //
  58. // }];
  59. CGRect rect=self.view.bounds;
  60. DebugLog(@"%@",NSStringFromCGRect(self.focusZone.frame));
  61. // rect.origin.y=rect.origin.y+40;
  62. // rect.size.height = rect.size.height-40;
  63. [CATransaction begin];
  64. [CATransaction setAnimationDuration:0.5];
  65. [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
  66. // [self updatePreviewLayerForOrientation:toInterfaceOrientation];
  67. _previewLayer.position = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
  68. // self.backgroundView.highLightRect = CGRectInset(self.focusZone.frame,6,6);
  69. _previewLayer.bounds = rect;
  70. UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
  71. switch (orientation) {
  72. case UIInterfaceOrientationPortrait:
  73. // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(0)];
  74. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortrait;
  75. break;
  76. case UIInterfaceOrientationPortraitUpsideDown:
  77. //[_previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI)];
  78. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortraitUpsideDown;
  79. break;
  80. case UIInterfaceOrientationLandscapeLeft:
  81. // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI/2)];
  82. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeLeft;
  83. break;
  84. case UIInterfaceOrientationLandscapeRight:
  85. // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(-M_PI/2)];
  86. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeRight;
  87. break;
  88. default:
  89. break;
  90. }
  91. [CATransaction commit];
  92. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  93. }
  94. //-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
  95. //{
  96. //
  97. //
  98. // [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
  99. // CGRect rect=self.view.bounds;
  100. //
  101. // DebugLog(@"%@",NSStringFromCGRect(self.focusZone.frame));
  102. // // rect.origin.y=rect.origin.y+40;
  103. // // rect.size.height = rect.size.height-40;
  104. //
  105. //
  106. //
  107. //
  108. //
  109. //
  110. //
  111. // [CATransaction begin];
  112. // [CATransaction setAnimationDuration:0.5];
  113. // [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
  114. //// [self updatePreviewLayerForOrientation:toInterfaceOrientation];
  115. // _previewLayer.position = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
  116. //
  117. // // self.backgroundView.highLightRect = CGRectInset(self.focusZone.frame,6,6);
  118. // _previewLayer.bounds = rect;
  119. //
  120. // UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
  121. // switch (orientation) {
  122. //
  123. //
  124. //
  125. // case UIInterfaceOrientationPortrait:
  126. // // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(0)];
  127. //
  128. // _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortrait;
  129. // break;
  130. // case UIInterfaceOrientationPortraitUpsideDown:
  131. // //[_previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI)];
  132. // _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortraitUpsideDown;
  133. // break;
  134. // case UIInterfaceOrientationLandscapeLeft:
  135. // // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI/2)];
  136. // _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeLeft;
  137. // break;
  138. // case UIInterfaceOrientationLandscapeRight:
  139. // // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(-M_PI/2)];
  140. // _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeRight;
  141. // break;
  142. // default:
  143. // break;
  144. // }
  145. // [CATransaction commit];
  146. //
  147. //
  148. //}
  149. //- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
  150. //{
  151. // return UIInterfaceOrientationPortrait;
  152. //}
  153. -(void) playSound
  154. {
  155. /*
  156. SystemSoundID sameViewSoundID;
  157. // NSString *filePath = [[NSBundle mainBundle]pathForResource:@"sound" ofType:@"m4r"];
  158. // NSString *thesoundFilePath = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"wav"]; //音乐文件路径
  159. NSString *path = @"/System/Library/Audio/UISounds/begin_video_record.caf";
  160. CFURLRef thesoundURL = (__bridge CFURLRef) [NSURL fileURLWithPath:path] ;
  161. AudioServicesCreateSystemSoundID(thesoundURL, &sameViewSoundID);
  162. //变量SoundID与URL对应
  163. DebugLog(@"%u",(unsigned int)sameViewSoundID);
  164. AudioServicesPlaySystemSound(1112); //播放SoundID声音
  165. */
  166. CFBundleRef mainBundle;
  167. SystemSoundID soundFileObject;
  168. mainBundle = CFBundleGetMainBundle ();
  169. CFURLRef soundFileURLRef = CFBundleCopyResourceURL (
  170. mainBundle,
  171. CFSTR ("softScanBeep" ),
  172. CFSTR ("wav" ),
  173. NULL
  174. );
  175. AudioServicesCreateSystemSoundID (
  176. soundFileURLRef,
  177. &soundFileObject
  178. );
  179. AudioServicesPlaySystemSound(soundFileObject);
  180. }
  181. - (void)viewWillAppear:(BOOL)animated
  182. {
  183. [super viewWillAppear:animated];
  184. [[self navigationController] setNavigationBarHidden:NO animated:NO];
  185. //
  186. //[ attemptRotationToDeviceOrientation];
  187. //[UIViewController attemptRotationToDeviceOrientation];
  188. //
  189. // [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait];
  190. // self.view.transform = CGAffineTransformMakeRotation(M_PI/2);
  191. // CGRect frame = [UIScreen mainScreen].applicationFrame;
  192. // self.view.bounds = CGRectMake(0, 0, 768, 1024);
  193. }
  194. - (void)onBackClick:(UIButton *)sender {
  195. [self.navigationController popViewControllerAnimated:FALSE];
  196. }
  197. - (void)viewDidLoad
  198. {
  199. [super viewDidLoad];
  200. UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
  201. style:UIBarButtonItemStylePlain
  202. target:self
  203. action:@selector( onBackClick:)];
  204. // closeButton.tintColor = UIColorFromRGB(0x996633);
  205. self.navigationItem.leftBarButtonItem = closeButton;
  206. }
  207. - (void)viewDidAppear:(BOOL)animated {
  208. [super viewDidAppear:animated];
  209. // 只有在此方法中取得的self.focusZone.frame才正确。
  210. // return;
  211. // [self.backgroundView removeFromSuperview];
  212. //self.back = (ScannerControllerView*)self.view;
  213. self.backgroundView.highLightRect = CGRectInset(self.focusZone.frame,6,6);
  214. [self.backgroundView setNeedsDisplay];
  215. // self.backgroundView.autoresizingMask=0xff;
  216. self.handelOutput = false;
  217. // self.ScannerControl =[self.storyboard instantiateViewControllerWithIdentifier:@"ScannerControlViewController"];
  218. // self.ScannerControl.Scannerdelegate = self;
  219. // self.view.layer.
  220. // Do any additional setup after loading the view, typically from a nib.
  221. // Create a new AVCaptureSession
  222. AVCaptureSession *session = [[AVCaptureSession alloc] init];
  223. session.sessionPreset = AVCaptureSessionPresetHigh;
  224. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  225. // float factor = device.videoZoomFactor;
  226. // float up = device.activeFormat.videoZoomFactorUpscaleThreshold;
  227. // [device lockForConfiguration:nil];
  228. // device.videoZoomFactor = device.activeFormat.videoZoomFactorUpscaleThreshold;
  229. // [device unlockForConfiguration];
  230. NSError *error = nil;
  231. // Want the normal device
  232. AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
  233. if(input) {
  234. // Add the input to the session
  235. [session addInput:input];
  236. } else {
  237. __weak typeof(self) weakself = self;
  238. // UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Warning" message:@"Camera access denied, please change iPad setting, allow App use camara. (setting -> privacy -> camera enable RA Image)" preferredStyle:UIAlertControllerStyleAlert];
  239. // UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  240. // [weakself dismissViewControllerAnimated:YES completion:nil];
  241. // }];
  242. // [alert addAction:action];
  243. // [self presentViewController:alert animated:YES completion:nil];
  244. if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { // 设备不可用
  245. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Warning" message:@"Camera is not available" preferredStyle:UIAlertControllerStyleAlert];
  246. UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  247. [weakself dismissViewControllerAnimated:YES completion:nil];
  248. }];
  249. [alert addAction:action];
  250. [self presentViewController:alert animated:YES completion:nil];
  251. return;
  252. }
  253. // 相机权限
  254. AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  255. if (authStatus ==AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。可能是家长控制权限
  256. authStatus ==AVAuthorizationStatusDenied) //用户已经明确否认了这一照片数据的应用程序访问
  257. {
  258. // 无权限 引导去开启
  259. // NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  260. // if ([[UIApplication sharedApplication]canOpenURL:url]) {
  261. // [[UIApplication sharedApplication]openURL:url];// 打开权限后返回应用会重启
  262. // } else {
  263. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  264. NSString *appName = [infoDict objectForKey:@"CFBundleName"];
  265. 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];
  266. UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  267. [weakself dismissViewControllerAnimated:YES completion:nil];
  268. }];
  269. [alert addAction:action];
  270. [self presentViewController:alert animated:YES completion:nil];
  271. // }
  272. return;
  273. }
  274. return;
  275. }
  276. AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
  277. // Have to add the output before setting metadata types
  278. [session addOutput:output];
  279. // What different things can we register to recognise?
  280. DebugLog(@"%@", [output availableMetadataObjectTypes]);
  281. // We're only interested in QR Codes
  282. [output setMetadataObjectTypes:@[AVMetadataObjectTypeUPCECode,AVMetadataObjectTypeCode39Code,AVMetadataObjectTypeCode39Mod43Code,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode93Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypePDF417Code,AVMetadataObjectTypeQRCode,AVMetadataObjectTypeAztecCode]];
  283. DebugLog(@"%@", [output metadataObjectTypes]);
  284. // NSArray* supporttype=output.availableMetadataObjectTypes;
  285. // [output setMetadataObjectTypes:output.availableMetadataObjectTypes];
  286. // This VC is the delegate. Please call us on the main queue
  287. [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
  288. //
  289. // CGRect rt1 = self.ScannerControl.scannerZone.frame;
  290. // Display on screen
  291. _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
  292. _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  293. // _previewLayer.orientation= AVCaptureVideoOrientationLandscapeRight;
  294. UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
  295. switch (orientation) {
  296. // UIInterfaceOrientationPortrait = UIDeviceOrientationPortrait,
  297. // UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
  298. // UIInterfaceOrientationLandscapeLeft = UIDeviceOrientationLandscapeRight,
  299. // UIInterfaceOrientationLandscapeRight
  300. // AVCaptureVideoOrientationPortrait = 1,
  301. // AVCaptureVideoOrientationPortraitUpsideDown = 2,
  302. // AVCaptureVideoOrientationLandscapeRight = 3,
  303. // AVCaptureVideoOrientationLandscapeLeft = 4,
  304. case UIInterfaceOrientationPortrait:
  305. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortrait;
  306. break;
  307. case UIInterfaceOrientationPortraitUpsideDown:
  308. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortraitUpsideDown;
  309. break;
  310. case UIInterfaceOrientationLandscapeLeft:
  311. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeLeft;
  312. break;
  313. case UIInterfaceOrientationLandscapeRight:
  314. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeRight;
  315. break;
  316. default:
  317. break;
  318. }
  319. CGRect rect=self.view.bounds;
  320. // rect.origin.y=rect.origin.y+40;
  321. // rect.size.height = rect.size.height-40;
  322. _previewLayer.bounds = rect;
  323. _previewLayer.position = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds));
  324. // [self.view.layer addSublayer:_previewLayer];
  325. [self.view.layer insertSublayer:_previewLayer atIndex:0];
  326. // [self.view addSubview:self.backgroundView];
  327. [self.view bringSubviewToFront:self.backgroundView];
  328. // [self.view addSubview:self.ScannerControl.view];
  329. // CGRect rt = self.ScannerControl.scannerZone.bounds;
  330. // CGRect rt1 =output.rectOfInterest;
  331. // output.rectOfInterest = CGRectMake(0, 0, 300, 300); //self.ScannerControl.scannerZone.frame;
  332. // ScannerControllerView* view =[[ ScannerControllerView alloc] initWithFrame:self.view.frame];
  333. // view.backgroundColor = [UIColor clearColor];
  334. // ScannerLayer * layer = [[ScannerLayer alloc] init];
  335. // [self.view.layer addSublayer:layer];
  336. // Add the view to draw the bounding box for the UIView
  337. _boundingBox = [[SCShapeView alloc] initWithFrame:self.view.bounds];
  338. _boundingBox.backgroundColor = [UIColor clearColor];
  339. _boundingBox.hidden = YES;
  340. [self.view insertSubview:_boundingBox belowSubview:self.backgroundView];
  341. // Add a label to display the resultant message
  342. _decodedMessage = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.bounds) - 75, CGRectGetWidth(self.view.bounds), 75)];
  343. _decodedMessage.numberOfLines = 0;
  344. _decodedMessage.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.9];
  345. _decodedMessage.textColor = [UIColor darkGrayColor];
  346. _decodedMessage.textAlignment = NSTextAlignmentCenter;
  347. [self.view addSubview:_decodedMessage];
  348. _decodedMessage.userInteractionEnabled = YES;
  349. UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  350. [backBtn setTitle:@"Cancel" forState:UIControlStateNormal];
  351. backBtn.titleLabel.backgroundColor = [UIColor clearColor];
  352. backBtn.titleLabel.font = [UIFont systemFontOfSize: 18.0];
  353. [backBtn setTitleColor:UIColorFromRGB(0x007aff) forState:UIControlStateNormal];
  354. backBtn.frame = CGRectMake(CGRectGetMaxX(self.view.frame) - 80, CGRectGetMaxY(self.view.frame)-CGRectGetHeight(_decodedMessage.frame), 60, CGRectGetHeight(_decodedMessage.frame));
  355. [self.view addSubview:backBtn];
  356. [backBtn addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
  357. self.scanButton.layer.shadowColor = [UIColor blackColor].CGColor;
  358. self.scanButton.layer.shadowOffset = CGSizeMake(0, 0);
  359. self.scanButton.layer.shadowOpacity = 0.5;
  360. self.scanButton.layer.shadowRadius = 2.0;
  361. self.scanButton.layer.borderColor = [[UIColor darkGrayColor] CGColor];
  362. self.scanButton.layer.borderWidth = 15;
  363. // Start the AVSession running
  364. [session startRunning];
  365. }
  366. - (void)backButtonClick:(UIButton *)sender {
  367. [self dismissViewControllerAnimated:YES completion:nil];
  368. }
  369. //#pragma mark - ScannerControllerDelegate
  370. //-(void)BeginScan:(bool)begin
  371. //{
  372. // self.handelOutput = begin;
  373. //}
  374. #pragma mark - AVCaptureMetadataOutputObjectsDelegate
  375. - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
  376. {
  377. if(!self.handelOutput)
  378. return;
  379. AVMetadataObject * cadedate = nil;
  380. CGPoint centerzone =CGPointMake(CGRectGetMidX(self.focusZone.frame), CGRectGetMidY(self.focusZone.frame));
  381. float distance = MAXFLOAT;
  382. for (AVMetadataObject *metadata in metadataObjects) {
  383. DebugLog(@"%@",metadata);
  384. // if ([metadata.type isEqualToString:AVMetadataObjectTypeQRCode])
  385. {
  386. // Transform the meta-data coordinates to screen coords
  387. AVMetadataMachineReadableCodeObject *transformed = (AVMetadataMachineReadableCodeObject *)[_previewLayer transformedMetadataObjectForMetadataObject:metadata];
  388. // Update the frame on the _boundingBox view, and show it
  389. CGRect rt = transformed.bounds;
  390. CGRectGetMidX(rt);
  391. CGPoint centermeta =CGPointMake(CGRectGetMidX(rt), CGRectGetMidY(rt));
  392. if(CGRectContainsPoint(self.focusZone.frame, centermeta))
  393. {
  394. if(cadedate == nil)
  395. cadedate = metadata;
  396. float distancemeta = (centermeta.x-centerzone.x)*(centermeta.x-centerzone.x)+(centermeta.y-centerzone.y)*(centermeta.y-centerzone.y);
  397. if(distancemeta<distance)
  398. {
  399. distance = distancemeta;
  400. cadedate = metadata;
  401. }
  402. }
  403. }
  404. }
  405. if(cadedate==nil)
  406. return;
  407. AVMetadataMachineReadableCodeObject *transformed = (AVMetadataMachineReadableCodeObject *)[_previewLayer transformedMetadataObjectForMetadataObject:cadedate];
  408. // Update the frame on the _boundingBox view, and show it
  409. // CGRect rt = transformed.bounds;
  410. _boundingBox.frame = transformed.bounds;
  411. _boundingBox.hidden = NO;
  412. // Now convert the corners array into CGPoints in the coordinate system
  413. // of the bounding box itself
  414. // NSArray * corners = transformed.corners;
  415. NSArray *translatedCorners = [self translatePoints:transformed.corners
  416. fromView:self.view
  417. toView:_boundingBox];
  418. // Set the corners array
  419. _boundingBox.corners = translatedCorners;
  420. // Update the view with the decoded text
  421. _decodedMessage.text = [transformed stringValue];
  422. // Start the timer which will hide the overlay
  423. [self startOverlayHideTimer];
  424. [self playSound];
  425. self.handelOutput = false;
  426. [self StopScan];
  427. self.scan_val = [transformed stringValue];
  428. [self dismissViewControllerAnimated:false completion:^{
  429. if(self.returnCode)
  430. self.returnCode(self.scan_val);
  431. }];
  432. }
  433. - (IBAction)ScanButtonClick:(id)sender {
  434. self.scanButton.backgroundColor = [UIColor greenColor];
  435. [self.scanButton setTitle:@"Scanning" forState:UIControlStateNormal];
  436. // self.scanButton.layer.borderWidth = 1;
  437. self.handelOutput = true;
  438. // if (self.Scannerdelegate && [self.Scannerdelegate respondsToSelector:@selector(BeginScan:)]) {
  439. // [self.Scannerdelegate BeginScan:true];
  440. // }
  441. }
  442. -(void) StopScan
  443. {
  444. self.scanButton.backgroundColor = [UIColor redColor];
  445. [self.scanButton setTitle:@"Tap" forState:UIControlStateNormal];
  446. }
  447. #pragma mark - Utility Methods
  448. - (void)startOverlayHideTimer
  449. {
  450. // Cancel it if we're already running
  451. if(_boxHideTimer) {
  452. [_boxHideTimer invalidate];
  453. }
  454. // Restart it to hide the overlay when it fires
  455. _boxHideTimer = [NSTimer scheduledTimerWithTimeInterval:0.2
  456. target:self
  457. selector:@selector(removeBoundingBox:)
  458. userInfo:nil
  459. repeats:NO];
  460. }
  461. - (void)removeBoundingBox:(id)sender
  462. {
  463. // Hide the box and remove the decoded text
  464. _boundingBox.hidden = YES;
  465. // _decodedMessage.text = @"";
  466. }
  467. - (NSArray *)translatePoints:(NSArray *)points fromView:(UIView *)fromView toView:(UIView *)toView
  468. {
  469. NSMutableArray *translatedPoints = [NSMutableArray new];
  470. // The points are provided in a dictionary with keys X and Y
  471. for (NSDictionary *point in points) {
  472. // Let's turn them into CGPoints
  473. CGPoint pointValue = CGPointMake([point[@"X"] floatValue], [point[@"Y"] floatValue]);
  474. // Now translate from one view to the other
  475. CGPoint translatedPoint = [fromView convertPoint:pointValue toView:toView];
  476. // Box them up and add to the array
  477. [translatedPoints addObject:[NSValue valueWithCGPoint:translatedPoint]];
  478. }
  479. return [translatedPoints copy];
  480. }
  481. @end