ScannerViewController.m 25 KB

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