LLSimpleCamera.m 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. //
  2. // CameraViewController.m
  3. // LLSimpleCamera
  4. //
  5. // Created by Ömer Faruk Gül on 24/10/14.
  6. // Copyright (c) 2014 Ömer Faruk Gül. All rights reserved.
  7. //
  8. #import "LLSimpleCamera.h"
  9. #import <ImageIO/CGImageProperties.h>
  10. #import "UIImage+FixOrientation.h"
  11. #import "LLSimpleCamera+Helper.h"
  12. @interface LLSimpleCamera () <AVCaptureFileOutputRecordingDelegate, UIGestureRecognizerDelegate>
  13. @property (strong, nonatomic) UIView *preview;
  14. @property (strong, nonatomic) AVCaptureStillImageOutput *stillImageOutput;
  15. @property (strong, nonatomic) AVCaptureSession *session;
  16. @property (strong, nonatomic) AVCaptureDevice *videoCaptureDevice;
  17. @property (strong, nonatomic) AVCaptureDeviceInput *videoDeviceInput;
  18. @property (strong, nonatomic) AVCaptureVideoPreviewLayer *captureVideoPreviewLayer;
  19. @property (strong, nonatomic) UITapGestureRecognizer *tapGesture;
  20. @property (strong, nonatomic) CALayer *focusBoxLayer;
  21. @property (strong, nonatomic) CAAnimation *focusBoxAnimation;
  22. @property (strong, nonatomic) AVCaptureMovieFileOutput *movieFileOutput;
  23. @property (strong, nonatomic) UIPinchGestureRecognizer *pinchGesture;
  24. @property (nonatomic, assign) CGFloat beginGestureScale;
  25. @property (nonatomic, assign) CGFloat effectiveScale;
  26. @property (nonatomic, copy) void (^didRecordCompletionBlock)(LLSimpleCamera *camera, NSURL *outputFileUrl, NSError *error);
  27. @end
  28. NSString *const LLSimpleCameraErrorDomain = @"LLSimpleCameraErrorDomain";
  29. @implementation LLSimpleCamera
  30. #pragma mark - Initialize
  31. - (instancetype)initWithQuality:(NSString *)quality position:(LLCameraPosition)position
  32. {
  33. self = [super initWithNibName:nil bundle:nil];
  34. if(self) {
  35. [self setupWithQuality:quality position:position];
  36. }
  37. return self;
  38. }
  39. - (instancetype)initWithCoder:(NSCoder *)aDecoder
  40. {
  41. if (self = [super initWithCoder:aDecoder]) {
  42. [self setupWithQuality:AVCaptureSessionPresetHigh
  43. position:LLCameraPositionRear];
  44. }
  45. return self;
  46. }
  47. - (void)setupWithQuality:(NSString *)quality
  48. position:(LLCameraPosition)position
  49. {
  50. _cameraQuality = quality;
  51. _position = position;
  52. _fixOrientationAfterCapture = NO;
  53. _tapToFocus = YES;
  54. _useDeviceOrientation = NO;
  55. _flash = LLCameraFlashOff;
  56. _mirror = LLCameraMirrorAuto;
  57. _recording = NO;
  58. _zoomingEnabled = YES;
  59. _effectiveScale = 1.0f;
  60. }
  61. - (void)viewDidLoad
  62. {
  63. [super viewDidLoad];
  64. self.view.backgroundColor = [UIColor clearColor];
  65. self.view.autoresizingMask = UIViewAutoresizingNone;
  66. self.preview = [[UIView alloc] initWithFrame:CGRectZero];
  67. self.preview.backgroundColor = [UIColor clearColor];
  68. [self.view addSubview:self.preview];
  69. // tap to focus
  70. self.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(previewTapped:)];
  71. self.tapGesture.numberOfTapsRequired = 1;
  72. [self.tapGesture setDelaysTouchesEnded:NO];
  73. [self.preview addGestureRecognizer:self.tapGesture];
  74. //pinch to zoom
  75. if (_zoomingEnabled) {
  76. self.pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
  77. self.pinchGesture.delegate = self;
  78. [self.preview addGestureRecognizer:self.pinchGesture];
  79. }
  80. // add focus box to view
  81. [self addDefaultFocusBox];
  82. }
  83. #pragma mark Pinch Delegate
  84. - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
  85. {
  86. if ( [gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]] ) {
  87. _beginGestureScale = _effectiveScale;
  88. }
  89. return YES;
  90. }
  91. - (void)handlePinchGesture:(UIPinchGestureRecognizer *)recognizer
  92. {
  93. BOOL allTouchesAreOnThePreviewLayer = YES;
  94. NSUInteger numTouches = [recognizer numberOfTouches], i;
  95. for ( i = 0; i < numTouches; ++i ) {
  96. CGPoint location = [recognizer locationOfTouch:i inView:self.preview];
  97. CGPoint convertedLocation = [self.preview.layer convertPoint:location fromLayer:self.view.layer];
  98. if ( ! [self.preview.layer containsPoint:convertedLocation] ) {
  99. allTouchesAreOnThePreviewLayer = NO;
  100. break;
  101. }
  102. }
  103. if (allTouchesAreOnThePreviewLayer) {
  104. _effectiveScale = _beginGestureScale * recognizer.scale;
  105. if (_effectiveScale < 1.0f)
  106. _effectiveScale = 1.0f;
  107. if (_effectiveScale > self.videoCaptureDevice.activeFormat.videoMaxZoomFactor)
  108. _effectiveScale = self.videoCaptureDevice.activeFormat.videoMaxZoomFactor;
  109. NSError *error = nil;
  110. if ([self.videoCaptureDevice lockForConfiguration:&error]) {
  111. [self.videoCaptureDevice rampToVideoZoomFactor:_effectiveScale withRate:100];
  112. [self.videoCaptureDevice unlockForConfiguration];
  113. } else {
  114. [self passError:error];
  115. }
  116. }
  117. }
  118. #pragma mark - Camera
  119. - (void)attachToViewController:(UIViewController *)vc withFrame:(CGRect)frame
  120. {
  121. [vc addChildViewController:self];
  122. self.view.frame = frame;
  123. [vc.view addSubview:self.view];
  124. [self didMoveToParentViewController:vc];
  125. }
  126. - (void)start
  127. {
  128. [LLSimpleCamera requestCameraPermission:^(BOOL granted) {
  129. if(granted) {
  130. [self initialize];
  131. }
  132. else {
  133. NSError *error = [NSError errorWithDomain:LLSimpleCameraErrorDomain code:LLSimpleCameraErrorCodeCameraPermission userInfo:nil];
  134. [self passError:error];
  135. }
  136. }];
  137. }
  138. - (void)initialize
  139. {
  140. if(!_session) {
  141. _session = [[AVCaptureSession alloc] init];
  142. _session.sessionPreset = self.cameraQuality;
  143. // preview layer
  144. CGRect bounds = self.preview.layer.bounds;
  145. _captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
  146. _captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  147. _captureVideoPreviewLayer.bounds = bounds;
  148. _captureVideoPreviewLayer.position = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));
  149. [self.preview.layer addSublayer:_captureVideoPreviewLayer];
  150. AVCaptureDevicePosition devicePosition;
  151. switch (self.position) {
  152. case LLCameraPositionRear:
  153. if([self.class isRearCameraAvailable]) {
  154. devicePosition = AVCaptureDevicePositionBack;
  155. } else {
  156. devicePosition = AVCaptureDevicePositionFront;
  157. _position = LLCameraPositionFront;
  158. }
  159. break;
  160. case LLCameraPositionFront:
  161. if([self.class isFrontCameraAvailable]) {
  162. devicePosition = AVCaptureDevicePositionFront;
  163. } else {
  164. devicePosition = AVCaptureDevicePositionBack;
  165. _position = LLCameraPositionRear;
  166. }
  167. break;
  168. default:
  169. devicePosition = AVCaptureDevicePositionUnspecified;
  170. break;
  171. }
  172. if(devicePosition == AVCaptureDevicePositionUnspecified) {
  173. self.videoCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  174. } else {
  175. self.videoCaptureDevice = [self cameraWithPosition:devicePosition];
  176. }
  177. NSError *error = nil;
  178. _videoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:_videoCaptureDevice error:&error];
  179. if (!_videoDeviceInput) {
  180. [self passError:error];
  181. return;
  182. }
  183. if([self.session canAddInput:_videoDeviceInput]) {
  184. [self.session addInput:_videoDeviceInput];
  185. self.captureVideoPreviewLayer.connection.videoOrientation = [self orientationForConnection];
  186. }
  187. // continiously adjust white balance
  188. self.whiteBalanceMode = AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance;
  189. // image output
  190. self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
  191. NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
  192. [self.stillImageOutput setOutputSettings:outputSettings];
  193. [self.session addOutput:self.stillImageOutput];
  194. }
  195. //if we had disabled the connection on capture, re-enable it
  196. if (![self.captureVideoPreviewLayer.connection isEnabled]) {
  197. [self.captureVideoPreviewLayer.connection setEnabled:YES];
  198. }
  199. [self.session startRunning];
  200. }
  201. - (void)stop
  202. {
  203. [self.session stopRunning];
  204. self.session = nil;
  205. }
  206. #pragma mark - Image Capture
  207. -(void)capture:(void (^)(LLSimpleCamera *camera, UIImage *image, NSDictionary *metadata, NSError *error))onCapture exactSeenImage:(BOOL)exactSeenImage animationBlock:(void (^)(AVCaptureVideoPreviewLayer *))animationBlock
  208. {
  209. if(!self.session) {
  210. NSError *error = [NSError errorWithDomain:LLSimpleCameraErrorDomain
  211. code:LLSimpleCameraErrorCodeSession
  212. userInfo:nil];
  213. onCapture(self, nil, nil, error);
  214. return;
  215. }
  216. // get connection and set orientation
  217. AVCaptureConnection *videoConnection = [self captureConnection];
  218. videoConnection.videoOrientation = [self orientationForConnection];
  219. BOOL flashActive = self.videoCaptureDevice.flashActive;
  220. if (!flashActive && animationBlock) {
  221. animationBlock(self.captureVideoPreviewLayer);
  222. }
  223. [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
  224. UIImage *image = nil;
  225. NSDictionary *metadata = nil;
  226. // check if we got the image buffer
  227. if (imageSampleBuffer != NULL) {
  228. CFDictionaryRef exifAttachments = CMGetAttachment(imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
  229. if(exifAttachments) {
  230. metadata = (__bridge NSDictionary*)exifAttachments;
  231. }
  232. NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
  233. image = [[UIImage alloc] initWithData:imageData];
  234. if(exactSeenImage) {
  235. image = [self cropImage:image usingPreviewLayer:self.captureVideoPreviewLayer];
  236. }
  237. if(self.fixOrientationAfterCapture) {
  238. image = [image fixOrientation];
  239. }
  240. }
  241. // trigger the block
  242. if(onCapture) {
  243. dispatch_async(dispatch_get_main_queue(), ^{
  244. onCapture(self, image, metadata, error);
  245. });
  246. }
  247. }];
  248. }
  249. -(void)capture:(void (^)(LLSimpleCamera *camera, UIImage *image, NSDictionary *metadata, NSError *error))onCapture exactSeenImage:(BOOL)exactSeenImage {
  250. [self capture:onCapture exactSeenImage:exactSeenImage animationBlock:^(AVCaptureVideoPreviewLayer *layer) {
  251. CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
  252. animation.duration = 0.1;
  253. animation.autoreverses = YES;
  254. animation.repeatCount = 0.0;
  255. animation.fromValue = [NSNumber numberWithFloat:1.0];
  256. animation.toValue = [NSNumber numberWithFloat:0.1];
  257. animation.fillMode = kCAFillModeForwards;
  258. animation.removedOnCompletion = NO;
  259. [layer addAnimation:animation forKey:@"animateOpacity"];
  260. }];
  261. }
  262. -(void)capture:(void (^)(LLSimpleCamera *camera, UIImage *image, NSDictionary *metadata, NSError *error))onCapture
  263. {
  264. [self capture:onCapture exactSeenImage:NO];
  265. }
  266. - (void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections
  267. {
  268. self.recording = YES;
  269. if(self.onStartRecording) self.onStartRecording(self);
  270. }
  271. - (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
  272. {
  273. self.recording = NO;
  274. [self enableTorch:NO];
  275. if(self.didRecordCompletionBlock) {
  276. self.didRecordCompletionBlock(self, outputFileURL, error);
  277. }
  278. }
  279. - (void)enableTorch:(BOOL)enabled
  280. {
  281. // check if the device has a torch, otherwise don't do anything
  282. if([self isTorchAvailable]) {
  283. AVCaptureTorchMode torchMode = enabled ? AVCaptureTorchModeOn : AVCaptureTorchModeOff;
  284. NSError *error;
  285. if ([self.videoCaptureDevice lockForConfiguration:&error]) {
  286. [self.videoCaptureDevice setTorchMode:torchMode];
  287. [self.videoCaptureDevice unlockForConfiguration];
  288. } else {
  289. [self passError:error];
  290. }
  291. }
  292. }
  293. #pragma mark - Helpers
  294. - (void)passError:(NSError *)error
  295. {
  296. if(self.onError) {
  297. __weak typeof(self) weakSelf = self;
  298. self.onError(weakSelf, error);
  299. }
  300. }
  301. - (AVCaptureConnection *)captureConnection
  302. {
  303. AVCaptureConnection *videoConnection = nil;
  304. for (AVCaptureConnection *connection in self.stillImageOutput.connections) {
  305. for (AVCaptureInputPort *port in [connection inputPorts]) {
  306. if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
  307. videoConnection = connection;
  308. break;
  309. }
  310. }
  311. if (videoConnection) {
  312. break;
  313. }
  314. }
  315. return videoConnection;
  316. }
  317. - (void)setVideoCaptureDevice:(AVCaptureDevice *)videoCaptureDevice
  318. {
  319. _videoCaptureDevice = videoCaptureDevice;
  320. if(videoCaptureDevice.flashMode == AVCaptureFlashModeAuto) {
  321. _flash = LLCameraFlashAuto;
  322. } else if(videoCaptureDevice.flashMode == AVCaptureFlashModeOn) {
  323. _flash = LLCameraFlashOn;
  324. } else if(videoCaptureDevice.flashMode == AVCaptureFlashModeOff) {
  325. _flash = LLCameraFlashOff;
  326. } else {
  327. _flash = LLCameraFlashOff;
  328. }
  329. _effectiveScale = 1.0f;
  330. // trigger block
  331. if(self.onDeviceChange) {
  332. __weak typeof(self) weakSelf = self;
  333. self.onDeviceChange(weakSelf, videoCaptureDevice);
  334. }
  335. }
  336. - (BOOL)isFlashAvailable
  337. {
  338. return self.videoCaptureDevice.hasFlash && self.videoCaptureDevice.isFlashAvailable;
  339. }
  340. - (BOOL)isTorchAvailable
  341. {
  342. return self.videoCaptureDevice.hasTorch && self.videoCaptureDevice.isTorchAvailable;
  343. }
  344. - (BOOL)updateFlashMode:(LLCameraFlash)cameraFlash
  345. {
  346. if(!self.session)
  347. return NO;
  348. AVCaptureFlashMode flashMode;
  349. if(cameraFlash == LLCameraFlashOn) {
  350. flashMode = AVCaptureFlashModeOn;
  351. } else if(cameraFlash == LLCameraFlashAuto) {
  352. flashMode = AVCaptureFlashModeAuto;
  353. } else {
  354. flashMode = AVCaptureFlashModeOff;
  355. }
  356. if([self.videoCaptureDevice isFlashModeSupported:flashMode]) {
  357. NSError *error;
  358. if([self.videoCaptureDevice lockForConfiguration:&error]) {
  359. self.videoCaptureDevice.flashMode = flashMode;
  360. [self.videoCaptureDevice unlockForConfiguration];
  361. _flash = cameraFlash;
  362. return YES;
  363. } else {
  364. [self passError:error];
  365. return NO;
  366. }
  367. }
  368. else {
  369. return NO;
  370. }
  371. }
  372. - (void)setWhiteBalanceMode:(AVCaptureWhiteBalanceMode)whiteBalanceMode
  373. {
  374. if ([self.videoCaptureDevice isWhiteBalanceModeSupported:whiteBalanceMode]) {
  375. NSError *error;
  376. if ([self.videoCaptureDevice lockForConfiguration:&error]) {
  377. [self.videoCaptureDevice setWhiteBalanceMode:whiteBalanceMode];
  378. [self.videoCaptureDevice unlockForConfiguration];
  379. } else {
  380. [self passError:error];
  381. }
  382. }
  383. }
  384. - (void)setMirror:(LLCameraMirror)mirror
  385. {
  386. _mirror = mirror;
  387. if(!self.session) {
  388. return;
  389. }
  390. AVCaptureConnection *videoConnection = [_movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
  391. AVCaptureConnection *pictureConnection = [_stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
  392. switch (mirror) {
  393. case LLCameraMirrorOff: {
  394. if ([videoConnection isVideoMirroringSupported]) {
  395. [videoConnection setVideoMirrored:NO];
  396. }
  397. if ([pictureConnection isVideoMirroringSupported]) {
  398. [pictureConnection setVideoMirrored:NO];
  399. }
  400. break;
  401. }
  402. case LLCameraMirrorOn: {
  403. if ([videoConnection isVideoMirroringSupported]) {
  404. [videoConnection setVideoMirrored:YES];
  405. }
  406. if ([pictureConnection isVideoMirroringSupported]) {
  407. [pictureConnection setVideoMirrored:YES];
  408. }
  409. break;
  410. }
  411. case LLCameraMirrorAuto: {
  412. BOOL shouldMirror = (_position == LLCameraPositionFront);
  413. if ([videoConnection isVideoMirroringSupported]) {
  414. [videoConnection setVideoMirrored:shouldMirror];
  415. }
  416. if ([pictureConnection isVideoMirroringSupported]) {
  417. [pictureConnection setVideoMirrored:shouldMirror];
  418. }
  419. break;
  420. }
  421. }
  422. return;
  423. }
  424. - (LLCameraPosition)togglePosition
  425. {
  426. if(!self.session) {
  427. return self.position;
  428. }
  429. if(self.position == LLCameraPositionRear) {
  430. self.cameraPosition = LLCameraPositionFront;
  431. } else {
  432. self.cameraPosition = LLCameraPositionRear;
  433. }
  434. return self.position;
  435. }
  436. - (void)setCameraPosition:(LLCameraPosition)cameraPosition
  437. {
  438. if(_position == cameraPosition || !self.session) {
  439. return;
  440. }
  441. if(cameraPosition == LLCameraPositionRear && ![self.class isRearCameraAvailable]) {
  442. return;
  443. }
  444. if(cameraPosition == LLCameraPositionFront && ![self.class isFrontCameraAvailable]) {
  445. return;
  446. }
  447. [self.session beginConfiguration];
  448. // remove existing input
  449. [self.session removeInput:self.videoDeviceInput];
  450. // get new input
  451. AVCaptureDevice *device = nil;
  452. if(self.videoDeviceInput.device.position == AVCaptureDevicePositionBack) {
  453. device = [self cameraWithPosition:AVCaptureDevicePositionFront];
  454. } else {
  455. device = [self cameraWithPosition:AVCaptureDevicePositionBack];
  456. }
  457. if(!device) {
  458. return;
  459. }
  460. // add input to session
  461. NSError *error = nil;
  462. AVCaptureDeviceInput *videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
  463. if(error) {
  464. [self passError:error];
  465. [self.session commitConfiguration];
  466. return;
  467. }
  468. _position = cameraPosition;
  469. [self.session addInput:videoInput];
  470. [self.session commitConfiguration];
  471. self.videoCaptureDevice = device;
  472. self.videoDeviceInput = videoInput;
  473. [self setMirror:_mirror];
  474. }
  475. // Find a camera with the specified AVCaptureDevicePosition, returning nil if one is not found
  476. - (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition) position
  477. {
  478. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  479. for (AVCaptureDevice *device in devices) {
  480. if (device.position == position) return device;
  481. }
  482. return nil;
  483. }
  484. #pragma mark - Focus
  485. - (void)previewTapped:(UIGestureRecognizer *)gestureRecognizer
  486. {
  487. if(!self.tapToFocus) {
  488. return;
  489. }
  490. CGPoint touchedPoint = [gestureRecognizer locationInView:self.preview];
  491. CGPoint pointOfInterest = [self convertToPointOfInterestFromViewCoordinates:touchedPoint
  492. previewLayer:self.captureVideoPreviewLayer
  493. ports:self.videoDeviceInput.ports];
  494. [self focusAtPoint:pointOfInterest];
  495. [self showFocusBox:touchedPoint];
  496. }
  497. - (void)addDefaultFocusBox
  498. {
  499. CALayer *focusBox = [[CALayer alloc] init];
  500. focusBox.cornerRadius = 5.0f;
  501. focusBox.bounds = CGRectMake(0.0f, 0.0f, 70, 60);
  502. focusBox.borderWidth = 3.0f;
  503. focusBox.borderColor = [[UIColor yellowColor] CGColor];
  504. focusBox.opacity = 0.0f;
  505. [self.view.layer addSublayer:focusBox];
  506. CABasicAnimation *focusBoxAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
  507. focusBoxAnimation.duration = 0.75;
  508. focusBoxAnimation.autoreverses = NO;
  509. focusBoxAnimation.repeatCount = 0.0;
  510. focusBoxAnimation.fromValue = [NSNumber numberWithFloat:1.0];
  511. focusBoxAnimation.toValue = [NSNumber numberWithFloat:0.0];
  512. [self alterFocusBox:focusBox animation:focusBoxAnimation];
  513. }
  514. - (void)alterFocusBox:(CALayer *)layer animation:(CAAnimation *)animation
  515. {
  516. self.focusBoxLayer = layer;
  517. self.focusBoxAnimation = animation;
  518. }
  519. - (void)focusAtPoint:(CGPoint)point
  520. {
  521. AVCaptureDevice *device = self.videoCaptureDevice;
  522. if (device.isFocusPointOfInterestSupported && [device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
  523. NSError *error;
  524. if ([device lockForConfiguration:&error]) {
  525. device.focusPointOfInterest = point;
  526. device.focusMode = AVCaptureFocusModeAutoFocus;
  527. [device unlockForConfiguration];
  528. } else {
  529. [self passError:error];
  530. }
  531. }
  532. }
  533. - (void)showFocusBox:(CGPoint)point
  534. {
  535. if(self.focusBoxLayer) {
  536. // clear animations
  537. [self.focusBoxLayer removeAllAnimations];
  538. // move layer to the touch point
  539. [CATransaction begin];
  540. [CATransaction setValue: (id) kCFBooleanTrue forKey: kCATransactionDisableActions];
  541. self.focusBoxLayer.position = point;
  542. [CATransaction commit];
  543. }
  544. if(self.focusBoxAnimation) {
  545. // run the animation
  546. [self.focusBoxLayer addAnimation:self.focusBoxAnimation forKey:@"animateOpacity"];
  547. }
  548. }
  549. #pragma mark - UIViewController
  550. - (void)viewWillAppear:(BOOL)animated
  551. {
  552. [super viewWillAppear:animated];
  553. }
  554. - (void)viewWillDisappear:(BOOL)animated
  555. {
  556. [super viewWillDisappear:animated];
  557. }
  558. - (void)viewWillLayoutSubviews
  559. {
  560. [super viewWillLayoutSubviews];
  561. self.preview.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
  562. CGRect bounds = self.preview.bounds;
  563. self.captureVideoPreviewLayer.bounds = bounds;
  564. self.captureVideoPreviewLayer.position = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));
  565. self.captureVideoPreviewLayer.connection.videoOrientation = [self orientationForConnection];
  566. }
  567. - (AVCaptureVideoOrientation)orientationForConnection
  568. {
  569. AVCaptureVideoOrientation videoOrientation = AVCaptureVideoOrientationPortrait;
  570. if(self.useDeviceOrientation) {
  571. switch ([UIDevice currentDevice].orientation) {
  572. case UIDeviceOrientationLandscapeLeft:
  573. // yes to the right, this is not bug!
  574. videoOrientation = AVCaptureVideoOrientationLandscapeRight;
  575. break;
  576. case UIDeviceOrientationLandscapeRight:
  577. videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
  578. break;
  579. case UIDeviceOrientationPortraitUpsideDown:
  580. videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
  581. break;
  582. default:
  583. videoOrientation = AVCaptureVideoOrientationPortrait;
  584. break;
  585. }
  586. }
  587. else {
  588. switch ([[UIApplication sharedApplication] statusBarOrientation]) {
  589. case UIInterfaceOrientationLandscapeLeft:
  590. videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
  591. break;
  592. case UIInterfaceOrientationLandscapeRight:
  593. videoOrientation = AVCaptureVideoOrientationLandscapeRight;
  594. break;
  595. case UIInterfaceOrientationPortraitUpsideDown:
  596. videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
  597. break;
  598. default:
  599. videoOrientation = AVCaptureVideoOrientationPortrait;
  600. break;
  601. }
  602. }
  603. return videoOrientation;
  604. }
  605. #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0
  606. - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
  607. {
  608. [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
  609. // layout subviews is not called when rotating from landscape right/left to left/right
  610. if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation) && UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
  611. [self.view setNeedsLayout];
  612. }
  613. }
  614. #else
  615. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
  616. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  617. // layout subviews is not called when rotating from landscape right/left to left/right
  618. [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context)
  619. {
  620. NSLog(@"转屏前调入");
  621. } completion:^(id<UIViewControllerTransitionCoordinatorContext> context)
  622. {
  623. NSLog(@"转屏后调入");
  624. }];
  625. [self.view setNeedsLayout];
  626. }
  627. #endif
  628. - (void)didReceiveMemoryWarning
  629. {
  630. [super didReceiveMemoryWarning];
  631. }
  632. - (void)dealloc {
  633. [self stop];
  634. }
  635. #pragma mark - Class Methods
  636. + (void)requestCameraPermission:(void (^)(BOOL granted))completionBlock
  637. {
  638. if ([AVCaptureDevice respondsToSelector:@selector(requestAccessForMediaType: completionHandler:)]) {
  639. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
  640. // return to main thread
  641. dispatch_async(dispatch_get_main_queue(), ^{
  642. if(completionBlock) {
  643. completionBlock(granted);
  644. }
  645. });
  646. }];
  647. } else {
  648. completionBlock(YES);
  649. }
  650. }
  651. + (BOOL)isFrontCameraAvailable
  652. {
  653. return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
  654. }
  655. + (BOOL)isRearCameraAvailable
  656. {
  657. return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
  658. }
  659. @end