经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » iOS » 查看文章
iOS开发技巧之自定义相机
来源:jb51  时间:2019/4/22 8:37:59  对本文有异议

最近公司的项目中用到了相机,由于不用系统的相机,UI给的相机切图,必须自定义才可以。就花时间简单研究了一下相机的自定义。

相机属于系统硬件,这就需要我们来手动调用iPhone的相机硬件,分为以下步骤:

1、首先声明以下对象

  1. #import <AVFoundation/AVFoundation.h>
  2. //捕获设备,通常是前置摄像头,后置摄像头,麦克风(音频输入)
  3. @property (nonatomic, strong) AVCaptureDevice *device;
  4. //AVCaptureDeviceInput 代表输入设备,他使用AVCaptureDevice 来初始化
  5. @property (nonatomic, strong) AVCaptureDeviceInput *input;
  6. //输出图片
  7. @property (nonatomic ,strong) AVCaptureStillImageOutput *imageOutput;
  8. //session:由他把输入输出结合在一起,并开始启动捕获设备(摄像头)
  9. @property (nonatomic, strong) AVCaptureSession *session;
  10. //图像预览层,实时显示捕获的图像
  11. @property (nonatomic ,strong) AVCaptureVideoPreviewLayer *previewLayer;

2、初始化各个对象

  1. - (void)cameraDistrict
  2. {
  3. // AVCaptureDevicePositionBack 后置摄像头
  4. // AVCaptureDevicePositionFront 前置摄像头
  5. self.device = [self cameraWithPosition:AVCaptureDevicePositionFront];
  6. self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:nil];
  7. self.imageOutput = [[AVCaptureStillImageOutput alloc] init];
  8. self.session = [[AVCaptureSession alloc] init];
  9. // 拿到的图像的大小可以自行设定
  10. // AVCaptureSessionPreset320x240
  11. // AVCaptureSessionPreset352x288
  12. // AVCaptureSessionPreset640x480
  13. // AVCaptureSessionPreset960x540
  14. // AVCaptureSessionPreset1280x720
  15. // AVCaptureSessionPreset1920x1080
  16. // AVCaptureSessionPreset3840x2160
  17. self.session.sessionPreset = AVCaptureSessionPreset640x480;
  18. //输入输出设备结合
  19. if ([self.session canAddInput:self.input]) {
  20. [self.session addInput:self.input];
  21. }
  22. if ([self.session canAddOutput:self.imageOutput]) {
  23. [self.session addOutput:self.imageOutput];
  24. }
  25. //预览层的生成
  26. self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
  27. self.previewLayer.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64);
  28. self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  29. [self.view.layer addSublayer:self.previewLayer];
  30. //设备取景开始
  31. [self.session startRunning];
  32. if ([_device lockForConfiguration:nil]) {
  33. //自动闪光灯,
  34. if ([_device isFlashModeSupported:AVCaptureFlashModeAuto]) {
  35. [_device setFlashMode:AVCaptureFlashModeAuto];
  36. }
  37. //自动白平衡,但是好像一直都进不去
  38. if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
  39. [_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
  40. }
  41. [_device unlockForConfiguration];
  42. }
  43. }

根据前后置位置拿到相应的摄像头:

  1. - (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
  2. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  3. for ( AVCaptureDevice *device in devices )
  4. if ( device.position == position ){
  5. return device;
  6. }
  7. return nil;
  8. }

3、拍照拿到相应图片:

  1. - (void)photoBtnDidClick
  2. {
  3. AVCaptureConnection *conntion = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
  4. if (!conntion) {
  5. NSLog(@"拍照失败!");
  6. return;
  7. }
  8. [self.imageOutput captureStillImageAsynchronouslyFromConnection:conntion completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
  9. if (imageDataSampleBuffer == nil) {
  10. return ;
  11. }
  12. NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
  13. self.image = [UIImage imageWithData:imageData];
  14. [self.session stopRunning];
  15. [self.view addSubview:self.cameraImageView];
  16. }

4、保存照片到相册:

  1. #pragma - 保存至相册
  2. - (void)saveImageToPhotoAlbum:(UIImage*)savedImage
  3. {
  4. UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
  5. }
  6. // 指定回调方法
  7. - (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
  8. {
  9. NSString *msg = nil ;
  10. if(error != NULL){
  11. msg = @"保存图片失败" ;
  12. }else{
  13. msg = @"保存图片成功" ;
  14. }
  15. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存图片结果提示"
  16. message:msg
  17. delegate:self
  18. cancelButtonTitle:@"确定"
  19. otherButtonTitles:nil];
  20. [alert show];
  21. }

5、前后置摄像头的切换

  1. - (void)changeCamera{
  2. NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
  3. if (cameraCount > 1) {
  4. NSError *error;
  5. //给摄像头的切换添加翻转动画
  6. CATransition *animation = [CATransition animation];
  7. animation.duration = .5f
  8. animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  9. animation.type = @"oglFlip";
  10. AVCaptureDevice *newCamera = nil;
  11. AVCaptureDeviceInput *newInput = nil;
  12. //拿到另外一个摄像头位置
  13. AVCaptureDevicePosition position = [[_input device] position];
  14. if (position == AVCaptureDevicePositionFront){
  15. newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
  16. animation.subtype = kCATransitionFromLeft;//动画翻转方向
  17. }
  18. else {
  19. newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
  20. animation.subtype = kCATransitionFromRight;//动画翻转方向
  21. }
  22. //生成新的输入
  23. newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
  24. [self.previewLayer addAnimation:animation forKey:nil];
  25. if (newInput != nil) {
  26. [self.session beginConfiguration];
  27. [self.session removeInput:self.input];
  28. if ([self.session canAddInput:newInput]) {
  29. [self.session addInput:newInput];
  30. self.input = newInput;
  31. } else {
  32. [self.session addInput:self.input];
  33. }
  34. [self.session commitConfiguration];
  35. } else if (error) {
  36. NSLog(@"toggle carema failed, error = %@", error);
  37. }
  38. }
  39. }

6、相机的其它参数设置

  1. //AVCaptureFlashMode 闪光灯
  2. //AVCaptureFocusMode 对焦
  3. //AVCaptureExposureMode 曝光
  4. //AVCaptureWhiteBalanceMode 白平衡
  5. //闪光灯和白平衡可以在生成相机时候设置
  6. //曝光要根据对焦点的光线状况而决定,所以和对焦一块写
  7. //point为点击的位置
  8. - (void)focusAtPoint:(CGPoint)point{
  9. CGSize size = self.view.bounds.size;
  10. CGPoint focusPoint = CGPointMake( point.y /size.height ,1-point.x/size.width );
  11. NSError *error;
  12. if ([self.device lockForConfiguration:&error]) {
  13. //对焦模式和对焦点
  14. if ([self.device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
  15. [self.device setFocusPointOfInterest:focusPoint];
  16. [self.device setFocusMode:AVCaptureFocusModeAutoFocus];
  17. }
  18. //曝光模式和曝光点
  19. if ([self.device isExposureModeSupported:AVCaptureExposureModeAutoExpose ]) {
  20. [self.device setExposurePointOfInterest:focusPoint];
  21. [self.device setExposureMode:AVCaptureExposureModeAutoExpose];
  22. }
  23. [self.device unlockForConfiguration];
  24. //设置对焦动画
  25. _focusView.center = point;
  26. _focusView.hidden = NO;
  27. [UIView animateWithDuration:0.3 animations:^{
  28. _focusView.transform = CGAffineTransformMakeScale(1.25, 1.25);
  29. }completion:^(BOOL finished) {
  30. [UIView animateWithDuration:0.5 animations:^{
  31. _focusView.transform = CGAffineTransformIdentity;
  32. } completion:^(BOOL finished) {
  33. _focusView.hidden = YES;
  34. }];
  35. }];
  36. }
  37. }

7、遇到的一些坑和解决办法

1) 前后置摄像头的切换

前后值不能切换,各种尝试找了半天没找到有原因。后来发现我在设置图片尺寸的时候设置为1080P [self.session canSetSessionPreset: AVCaptureSessionPreset1920x1080] ,前置摄像头并不支持这么大的尺寸,所以就不能切换前置摄像头。我验证了下 前置摄像头最高支持720P,720P以内可自由切换。  

当然也可以在前后置摄像头切换的时候,根据前后摄像头来设置不同的尺寸,这里不在赘述。

2)焦点位置

CGPoint focusPoint = CGPointMake( point.y /size.height ,1-point.x/size.width );
setExposurePointOfInterest:focusPoint 函数后面Point取值范围是取景框左上角(0,0)到取景框右下角(1,1)之间。官方是这么写的:

  The value of this property is a CGPoint that determines the receiver's focus point of interest, if it has one. A value of (0,0) indicates that the camera should focus on the top left corner of the image, while a value of (1,1) indicates that it should focus on the bottom right. The default value is (0.5,0.5).

我也试了按这个来但位置就是不对,只能按上面的写法才可以。前面是点击位置的y/PreviewLayer的高度,后面是1-点击位置的x/PreviewLayer的宽度

3)对焦和曝光

  我在设置对焦是 先设置了模式setFocusMode,后设置对焦位置,就会导致很奇怪的现象,对焦位置是你上次点击的位置。所以一定要先设置位置,再设置对焦模式。
  曝光同上

8、写在最后

附上demo:photographDemo

常用到的基本就这么多,写的并不完善,有什么不对的,欢迎大家批评指正,共同学习。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号