RACameraViewController.m 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. //
  2. // RACameraViewController.m
  3. // Apex And Drivers
  4. //
  5. // Created by Jack on 2018/6/5.
  6. // Copyright © 2018年 USAI. All rights reserved.
  7. //
  8. #import "RACameraViewController.h"
  9. #import <AVFoundation/AVFoundation.h>
  10. #import "RATakePhotoPreviewController.h"
  11. #import <CoreMotion/CoreMotion.h>
  12. @interface RACameraViewController ()<AVCapturePhotoCaptureDelegate>
  13. @property (nonatomic,strong) IBOutlet UIView *previewContainer;
  14. @property (nonatomic,strong) IBOutlet UIView *controlContanier;
  15. @property (strong, nonatomic) IBOutlet UIButton *takePhotoBtn;
  16. @property (strong, nonatomic) IBOutlet UIButton *backBtn;
  17. @property (nonatomic,assign) BOOL barHidden;
  18. #pragma mark - Camera
  19. @property (nonatomic,strong) AVCaptureDevice *captureDevice;
  20. @property (nonatomic,strong) AVCaptureSession *captureSession;
  21. @property (nonatomic,strong) AVCaptureDeviceInput *captureInput;
  22. //@property (nonatomic,strong) AVCaptureStillImageOutput *captureOutput;
  23. @property (nonatomic,strong) AVCapturePhotoSettings *photoSetting;
  24. @property (nonatomic,strong) AVCapturePhotoOutput* photoOutput;
  25. @property (nonatomic,strong) AVCaptureVideoPreviewLayer *previewLayer;
  26. @property (nonatomic,assign) BOOL cameraInitial;
  27. @property (nonatomic,assign) AVLayerVideoGravity gravity;
  28. @property (strong, nonatomic) CMMotionManager *motionManager;
  29. @property (assign, nonatomic) UIDeviceOrientation orientationLast;
  30. @end
  31. @implementation RACameraViewController
  32. -(BOOL)shouldAutorotate {
  33. return NO;
  34. }
  35. - (void)initMotionManager
  36. {
  37. if (_motionManager == nil) {
  38. _motionManager = [[CMMotionManager alloc] init];
  39. }
  40. // 提供设备运动数据到指定的时间间隔
  41. _motionManager.deviceMotionUpdateInterval = .3;
  42. if (_motionManager.deviceMotionAvailable) { // 确定是否使用任何可用的态度参考帧来决定设备的运动是否可用
  43. [_motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue]
  44. withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
  45. if (!error) {
  46. [self outputAccelertionData:accelerometerData.acceleration];
  47. }
  48. else{
  49. NSLog(@"%@", error);
  50. }
  51. }];
  52. }else
  53. {
  54. [self setMotionManager:nil];
  55. }
  56. }
  57. - (void)outputAccelertionData:(CMAcceleration)acceleration{
  58. UIDeviceOrientation orientationNew;
  59. // NSLog(@"x %f y %f z %f",acceleration.x,acceleration.y, acceleration.z);
  60. if (acceleration.x >= 0.75) {
  61. orientationNew = UIDeviceOrientationLandscapeRight;
  62. }
  63. else if (acceleration.x <= -0.75) {
  64. orientationNew = UIDeviceOrientationLandscapeLeft;
  65. }
  66. else if (acceleration.y <= -0.75) {
  67. orientationNew = UIDeviceOrientationPortrait;
  68. }
  69. else if (acceleration.y >= 0.75) {
  70. orientationNew = UIDeviceOrientationPortraitUpsideDown;
  71. }
  72. else {
  73. // Consider same as last time
  74. return;
  75. }
  76. if (orientationNew == self.orientationLast)
  77. return;
  78. self.orientationLast = orientationNew;
  79. // [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:orientationNew] forKey:@"orientation"];
  80. // CGRect frame = self.previewContainer.bounds;
  81. // [self resetPreview:frame];
  82. }
  83. + (NSString *)storyboardID {
  84. return NSStringFromClass([self class]);
  85. }
  86. + (instancetype)viewControllerFromStoryboard {
  87. RACameraViewController *cameraVC = [[UIStoryboard storyboardWithName:@"Camera" bundle:nil] instantiateViewControllerWithIdentifier:[self storyboardID]];
  88. cameraVC.takeMode = RACameraTakeModeTakeOnce;
  89. cameraVC.gravity = AVLayerVideoGravityResizeAspectFill;
  90. return cameraVC;
  91. }
  92. + (instancetype)showCameraFromViewController:(UIViewController *)from withTakeMode:(RACameraTakeMode)mode videoGravity:(AVLayerVideoGravity)gravity completion:(void(^)(UIImage *image))completion {
  93. RACameraViewController *vc = [self viewControllerFromStoryboard];
  94. vc.takeMode = mode;
  95. if (!gravity) {
  96. gravity = AVLayerVideoGravityResizeAspectFill;
  97. }
  98. vc.gravity = gravity;
  99. vc.completion = completion;
  100. return vc;
  101. }
  102. - (void)viewDidLoad {
  103. [super viewDidLoad];
  104. // Do any additional setup after loading the view.
  105. [self initMotionManager];
  106. UIImage *normal_img = [self.class imageWithColor:[UIColor redColor] Size:CGSizeMake(60, 60)];
  107. UIImage *highlight_img = [self.class imageWithColor:[UIColor whiteColor] Size:CGSizeMake(60, 60)];
  108. [self.takePhotoBtn setImage:normal_img forState:UIControlStateNormal];
  109. [self.takePhotoBtn setImage:highlight_img forState:UIControlStateHighlighted];
  110. // [self initCapture];
  111. // [self initTakePicture];
  112. if ([self camerAuthorization]) {
  113. [self initCapture];
  114. [self initTakePicture];
  115. } else {
  116. // fix:第一次打开相机的时候授权成功后,未初始化相机
  117. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
  118. dispatch_async(dispatch_get_main_queue(), ^{
  119. if (granted) {
  120. [self initCapture];
  121. [self initTakePicture];
  122. CGRect frame = self.previewContainer.bounds;
  123. [self resetPreview:CGRectOffset(frame, CGRectGetWidth(frame), 0)];
  124. [UIView animateWithDuration:0.3 animations:^{
  125. self.previewLayer.frame = frame;
  126. }];
  127. if (self.cameraInitial && !self.captureSession.isRunning) {
  128. // [self.captureSession startRunning];
  129. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  130. [self.captureSession startRunning];
  131. // sleep(0.3);
  132. // dispatch_async(dispatch_get_main_queue(), ^{
  133. // [self.mask removeFromSuperview];
  134. // });
  135. });
  136. }
  137. } else {
  138. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  139. NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
  140. if (!appName) {
  141. appName = [infoDict objectForKey:@"CFBundleName"];
  142. }
  143. __weak typeof(self) weakSelf = self;
  144. 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];
  145. UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  146. [weakSelf dismissViewControllerAnimated:YES completion:nil];
  147. }];
  148. [alert addAction:action];
  149. [self presentViewController:alert animated:YES completion:nil];
  150. }
  151. });
  152. }];
  153. }
  154. /**
  155. * 管理导航条
  156. * 在viewDidload的时候隐藏导航条
  157. * 恢复导航条的显示/隐藏有两个地方:1.退出的时候;2.确认使用照片的时候
  158. */
  159. if (self.navigationController) {
  160. BOOL navBarHidden = self.navigationController.navigationBar.hidden;
  161. self.barHidden = navBarHidden;
  162. if (!navBarHidden) {
  163. [self.navigationController setNavigationBarHidden:YES animated:YES];
  164. }
  165. }
  166. }
  167. - (void)didReceiveMemoryWarning {
  168. [super didReceiveMemoryWarning];
  169. // Dispose of any resources that can be recreated.
  170. }
  171. - (void)viewWillAppear:(BOOL)animated {
  172. [super viewWillAppear:animated];
  173. if (self.cameraInitial && !self.captureSession.isRunning) {
  174. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  175. [self.captureSession startRunning];
  176. // sleep(0.3);
  177. // dispatch_async(dispatch_get_main_queue(), ^{
  178. // [self.mask removeFromSuperview];
  179. // });
  180. });
  181. }
  182. }
  183. - (void)viewWillDisappear:(BOOL)animated {
  184. [super viewWillDisappear:animated];
  185. if ([self.captureSession isRunning]) {
  186. [self.captureSession stopRunning];
  187. }
  188. }
  189. - (BOOL)prefersStatusBarHidden {
  190. return YES;
  191. }
  192. - (void)viewDidLayoutSubviews {
  193. [super viewDidLayoutSubviews];
  194. // 强制布局一次,不然 takePhotoBtn frame还没发生改变
  195. [self.controlContanier layoutIfNeeded];
  196. if ([self camerAuthorization] && self.cameraInitial) {
  197. CGRect frame = self.previewContainer.bounds;
  198. BOOL isPortrait = self.interfaceOrientation == UIInterfaceOrientationPortrait || self.interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown;
  199. // aspect ratio 3:4
  200. if (self.gravity == AVLayerVideoGravityResizeAspect) {
  201. CGRect backBtnFrame = [self.previewContainer convertRect:self.backBtn.frame fromView:self.controlContanier];
  202. CGRect captureBtnFrame = [self.previewContainer convertRect:self.takePhotoBtn.frame fromView:self.controlContanier];
  203. if (isPortrait) {
  204. CGFloat left = 0;
  205. CGFloat top = CGRectGetMaxY(backBtnFrame);
  206. CGFloat bottom = CGRectGetMinY(captureBtnFrame);
  207. CGFloat width = CGRectGetWidth(self.controlContanier.bounds);
  208. CGFloat height = bottom - top;
  209. frame = CGRectMake(left, top, width, height);
  210. } else {
  211. CGFloat left = CGRectGetMaxX(backBtnFrame);
  212. CGFloat right = CGRectGetMinX(captureBtnFrame);
  213. CGFloat top = 0;
  214. CGFloat width = right - left;
  215. CGFloat bottom = CGRectGetHeight(self.controlContanier.bounds);
  216. CGFloat height = bottom - top;
  217. frame = CGRectMake(left, top, width, height);
  218. }
  219. }
  220. [self resetPreview:frame];
  221. }
  222. }
  223. #pragma mark - Capture
  224. - (void)resetPreview:(CGRect)frame {
  225. self.previewLayer.frame = frame;
  226. // if (self.previewLayer.connection.isVideoOrientationSupported) {
  227. // self.previewLayer.connection.videoOrientation = [self captureVideoOrientation];
  228. // }
  229. //
  230. // if ([self.captureOutput connectionWithMediaType:AVMediaTypeVideo].isVideoOrientationSupported) {
  231. // [self.captureOutput connectionWithMediaType:AVMediaTypeVideo].videoOrientation = [self captureVideoOrientation];
  232. // }
  233. //
  234. }
  235. - (BOOL)camerAuthorization {
  236. AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  237. if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) {
  238. return NO;
  239. }
  240. return YES;
  241. }
  242. - (void)initCapture {
  243. self.cameraInitial = NO;
  244. if (![self camerAuthorization]) {
  245. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  246. NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
  247. if (!appName) {
  248. appName = [infoDict objectForKey:@"CFBundleName"];
  249. }
  250. __weak typeof(self) weakSelf = self;
  251. 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];
  252. UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  253. [weakSelf dismissViewControllerAnimated:YES completion:nil];
  254. }];
  255. [alert addAction:action];
  256. [self presentViewController:alert animated:YES completion:nil];
  257. return;
  258. }
  259. self.captureSession = [[AVCaptureSession alloc] init];
  260. self.captureDevice = [self videoDevicePosition:AVCaptureDevicePositionBack];
  261. if (!self.captureDevice) {
  262. NSLog(@"there is no capture device while init camera");
  263. return;
  264. }
  265. NSError *error;
  266. self.captureInput = [[AVCaptureDeviceInput alloc] initWithDevice:self.captureDevice error:&error];
  267. if (error) {
  268. NSLog(@"init camera error: %@",error);
  269. return;
  270. }
  271. [self.captureSession beginConfiguration];
  272. if ([_captureSession canSetSessionPreset:AVCaptureSessionPresetPhoto]) {
  273. _captureSession.sessionPreset = AVCaptureSessionPresetPhoto;
  274. }
  275. // if ([self.captureDevice isFlashAvailable] && [_captureDevice isFlashModeSupported:AVCaptureFlashModeAuto]) {
  276. if ([self.captureDevice isFlashAvailable] && [self.photoOutput supportedFlashModes]) {
  277. NSError *configErr;
  278. [self.captureDevice lockForConfiguration:&configErr];
  279. // AVCapturePhotoSettings.flashMode
  280. // [self.captureDevice setFlashMode:AVCaptureFlashModeAuto];
  281. [self.captureDevice unlockForConfiguration];
  282. }
  283. // if ([self.captureDevice isAdjustingWhiteBalance] && [self.captureDevice isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
  284. // NSError *configErr;
  285. // [self.captureDevice lockForConfiguration:&configErr];
  286. // [self.captureDevice setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
  287. // [self.captureDevice unlockForConfiguration];
  288. // }
  289. if ([self.captureSession canAddInput:self.captureInput]) {
  290. [self.captureSession addInput:self.captureInput];
  291. // if ([self.captureSession canSetSessionPreset:AVCaptureSessionPreset1920x1080]) {
  292. // self.captureSession.sessionPreset = AVCaptureSessionPreset1920x1080;
  293. // } else {
  294. // if ([self.captureSession canSetSessionPreset:AVCaptureSessionPresetHigh]) {
  295. // self.captureSession.sessionPreset = AVCaptureSessionPresetHigh;
  296. // }
  297. // }
  298. } else {
  299. NSLog(@"init camera can't add input");
  300. return;
  301. }
  302. [self.captureSession commitConfiguration];
  303. self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
  304. self.previewLayer.videoGravity = self.gravity;
  305. [self.previewContainer.layer addSublayer:self.previewLayer];
  306. self.cameraInitial = YES;
  307. }
  308. - (void)initTakePicture {
  309. if (!self.cameraInitial) {
  310. return;
  311. }
  312. // self.captureOutput = [[AVCaptureStillImageOutput alloc] init];
  313. self.photoOutput = [AVCapturePhotoOutput new];
  314. // NSDictionary *setting = @{AVVideoCodecKey:AVVideoCodecJPEG};
  315. // AVVideoCodecTypeJPEG
  316. // self.photoSetting.cod
  317. // [self.captureOutput setOutputSettings:setting];
  318. //
  319. if ([self.captureSession canAddOutput:self.photoOutput]) {
  320. [self.captureSession addOutput:self.photoOutput];
  321. }
  322. // AVCaptureConnection *connection = [self.captureOutput connectionWithMediaType:AVMediaTypeVideo];
  323. // if (connection.isVideoOrientationSupported) { // addOutput之后判断,否则一直都是false
  324. // connection.videoOrientation = [self captureVideoOrientation];
  325. // }
  326. }
  327. - (AVCaptureDevice *) videoDevicePosition:(AVCaptureDevicePosition)position {
  328. // NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  329. AVCaptureDeviceDiscoverySession * _Nonnull cameras = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera] mediaType:AVMediaTypeVideo position: AVCaptureDevicePositionUnspecified];//AVCaptureDevicePositionFront & AVCaptureDevicePositionBack
  330. // //获取当前摄像头方向
  331. // AVCaptureDevicePosition currentPosition = self.captureDeviceInput.device.position;
  332. // AVCaptureDevicePosition toPosition = AVCaptureDevicePositionUnspecified;
  333. // if (currentPosition == AVCaptureDevicePositionBack || currentPosition == AVCaptureDevicePositionUnspecified) {
  334. // toPosition = AVCaptureDevicePositionFront;
  335. // }else{
  336. // toPosition = AVCaptureDevicePositionBack;
  337. // }
  338. // NSArray* captureDeviceArray = [cameras.devices filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"position == %d",toPosition]];
  339. // if (captureDeviceArray.count == 0) {
  340. // return [self throw_errorWithDomain:@"VideoCapture: reverseCamera failed! get new camera failed!"];
  341. // }
  342. for (AVCaptureDevice *device in cameras.devices) {
  343. if ([device position] == position) {
  344. return device;
  345. }
  346. }
  347. return nil;
  348. }
  349. - (AVCaptureVideoOrientation)captureVideoOrientation {
  350. AVCaptureVideoOrientation result;
  351. // UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
  352. switch (self.orientationLast) {
  353. case UIDeviceOrientationPortrait:
  354. case UIDeviceOrientationFaceUp:
  355. case UIDeviceOrientationFaceDown:
  356. result = AVCaptureVideoOrientationPortrait;
  357. break;
  358. case UIDeviceOrientationPortraitUpsideDown:
  359. //如果这里设置成AVCaptureVideoOrientationPortraitUpsideDown,则视频方向和拍摄时的方向是相反的。
  360. result = AVCaptureVideoOrientationPortraitUpsideDown;
  361. break;
  362. case UIDeviceOrientationLandscapeLeft:
  363. result = AVCaptureVideoOrientationLandscapeRight;
  364. break;
  365. case UIDeviceOrientationLandscapeRight:
  366. result = AVCaptureVideoOrientationLandscapeLeft;
  367. break;
  368. default:
  369. result = AVCaptureVideoOrientationPortrait;
  370. break;
  371. }
  372. return result;
  373. }
  374. #pragma mark - Action
  375. - (IBAction)takePictureBtnClick:(UIButton *)sender {
  376. // UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
  377. // NSLog(@"UIDeviceOrientation %ld",deviceOrientation);
  378. // [self.captureOutput connectionWithMediaType:AVMediaTypeVideo];
  379. if (!self.cameraInitial) {
  380. return;
  381. }
  382. sender.enabled = false;
  383. // AVCaptureConnection *connection = [self.captureOutput connectionWithMediaType:AVMediaTypeVideo];
  384. //
  385. // if (connection.isVideoOrientationSupported) { // addOutput之后判断,否则一直都是false
  386. // connection.videoOrientation = [self captureVideoOrientation];
  387. // }
  388. //
  389. // NSLog(@"capture orientation %ld",connection.videoOrientation);
  390. ;
  391. // __weak typeof(self) weakSelf = self;
  392. self.photoSetting= [AVCapturePhotoSettings photoSettings];
  393. if(self.captureDevice.hasFlash)
  394. {
  395. self.photoSetting.flashMode =AVCaptureFlashModeAuto;
  396. }
  397. [self.photoOutput capturePhotoWithSettings:self.photoSetting delegate:self];
  398. //
  399. // [self.captureOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:^(CMSampleBufferRef _Nullable imageDataSampleBuffer, NSError * _Nullable error) {
  400. //
  401. // if (imageDataSampleBuffer) {
  402. // NSData *imageData=[AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
  403. // UIImage *image=[UIImage imageWithData:imageData];
  404. //
  405. // RATakePhotoPreviewController *preVC = [RATakePhotoPreviewController viewControllerFromStoryboard];
  406. // preVC.photoHandler = ^(UIImage *img){
  407. // if (weakSelf) {
  408. // __strong typeof(weakSelf) strongSelf = weakSelf;
  409. // if (strongSelf.completion) {
  410. // strongSelf.completion(img);
  411. // }
  412. // }
  413. // };
  414. // preVC.preImage = image;
  415. // if (weakSelf.takeMode == RACameraTakeModeTakeOnce) {
  416. // preVC.popTo = weakSelf.fromVC;
  417. // preVC.barHidden = weakSelf.barHidden;
  418. // }
  419. // [weakSelf.navigationController pushViewController:preVC animated:YES];
  420. //
  421. // } else {
  422. // NSLog(@"take picture failed: %@",error);
  423. // }
  424. // sender.enabled = true;
  425. // }];
  426. }
  427. - (IBAction)returnButtonClick:(UIButton *)sender {
  428. if (self.navigationController) {
  429. [self.navigationController popViewControllerAnimated:YES];
  430. } else {
  431. [self dismissViewControllerAnimated:YES completion:nil];
  432. }
  433. if (self.navigationController) {
  434. [self.navigationController setNavigationBarHidden:self.barHidden animated:YES];
  435. }
  436. }
  437. #pragma mark - Utils
  438. + (UIImage *)imageWithColor:(UIColor *)color Size:(CGSize)size {
  439. UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
  440. CGContextRef ctx = UIGraphicsGetCurrentContext();
  441. CGContextAddEllipseInRect(ctx, CGRectMake(5, 5, size.width - 10, size.height - 10));
  442. CGContextSetFillColorWithColor(ctx, color.CGColor);
  443. CGContextSetStrokeColorWithColor(ctx, [UIColor whiteColor].CGColor);
  444. CGContextSetLineWidth(ctx, 3.0f);
  445. CGContextDrawPath(ctx, kCGPathFillStroke);
  446. UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
  447. UIGraphicsEndImageContext();
  448. return img;
  449. }
  450. #pragma mark - AVCapturePhotoCaptureDelegate
  451. -(void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error API_AVAILABLE(ios(11.0)) {
  452. if (!error) {
  453. // 使用该方式获取图片,可能图片会存在旋转问题,在使用的时候调整图片即可
  454. NSData *imageData = [photo fileDataRepresentation];
  455. UIImage *image = [UIImage imageWithData:imageData];
  456. // NSData *imageData=[AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
  457. // UIImage *image=[UIImage imageWithData:imageData];
  458. RATakePhotoPreviewController *preVC = [RATakePhotoPreviewController viewControllerFromStoryboard];
  459. preVC.photoHandler = ^(UIImage *img){
  460. if (self.completion) {
  461. self.completion(img);
  462. }
  463. };
  464. preVC.preImage = image;
  465. if (self.takeMode == RACameraTakeModeTakeOnce) {
  466. preVC.popTo = self.fromVC;
  467. preVC.barHidden = self.barHidden;
  468. }
  469. [self.navigationController pushViewController:preVC animated:YES];
  470. } else {
  471. NSLog(@"take picture failed: %@",error);
  472. }
  473. // sender.enabled = true;
  474. self.takePhotoBtn.enabled = true;
  475. }
  476. @end