概述
1.方法一:截屏:
WYPCustomCameraVC:
//
// WYPCustomCameraVC.h
// RockUnion
//
// Created by 王彦平 on 2021/12/28.
// Copyright © 2021 王彦平. All rights reserved.
//
#import "WYPBaseVC.h"
#import "WYPCustomCameraView.h"
NS_ASSUME_NONNULL_BEGIN
@protocol PopCameraControllerDelegate <NSObject>
-(void)popControllerWithImage:(UIImage *)image;
@end
@interface WYPCustomCameraVC : WYPBaseVC
@property (nonatomic, weak) id<PopCameraControllerDelegate>delegate;
//0身份证正面//1身份证反面//2银行卡
@property (nonatomic, assign) WYPCameraActionType cameraType;
@end
NS_ASSUME_NONNULL_END
//
// WYPCustomCameraVC.m
// RockUnion
//
// Created by 王彦平 on 2021/12/28.
// Copyright © 2021 王彦平. All rights reserved.
//
#import "WYPCustomCameraVC.h"
#import <AVFoundation/AVFoundation.h>
@interface WYPCustomCameraVC ()<AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate>
@property (nonatomic, strong) WYPCustomCameraView *cameraView;
@property (nonatomic, strong)UIImageView *preView;
//捕获设备,通常是前置摄像头,后置摄像头,麦克风(音频输入)
@property(nonatomic)AVCaptureDevice *device;
//AVCaptureDeviceInput 代表输入设备,他使用AVCaptureDevice 来初始化
@property(nonatomic)AVCaptureDeviceInput *input;
//当启动摄像头开始捕获输入
@property(nonatomic)AVCaptureMetadataOutput *output;
@property (nonatomic)AVCaptureStillImageOutput *ImageOutPut;
//session:由他把输入输出结合在一起,并开始启动捕获设备(摄像头)
@property(nonatomic)AVCaptureSession *session;
//图像预览层,实时显示捕获的图像
@property(nonatomic)AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic)BOOL isflashOn;
@property (nonatomic)UIImage *image;
@property (nonatomic)UIImageView *imageView;
@property (nonatomic)BOOL canCa;
@end
@implementation WYPCustomCameraVC
#pragma mark - lazy
-(WYPCustomCameraView *)cameraView{
if (!_cameraView) {
_cameraView = [WYPCustomCameraView WYPCustomCameraView];
WS(weakSelf);
_cameraView.btnBlock = ^(NSInteger tag) {
[weakSelf cameraViewBtnClickedWithTag:tag];
};
}
return _cameraView;
}
- (void)viewDidLoad {
[super viewDidLoad];
_canCa = [self canUserCamear];
if (_canCa) {
[self customCamera];
[self setUI];
}else{
return;
}
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self setNav];
}
//设置状态栏
-(void)setNav{
// 设置状态栏
[Tools setStatusBarBackgroundColor:[UIColor clearColor]];
self.navigationController.navigationBar.hidden = YES;
[UIApplication sharedApplication].statusBarHidden = YES;
}
//设置UI
-(void)setUI{
self.cameraView.cameraType = self.cameraType;
self.view.backgroundColor = [UIColor clearColor];
self.cameraView.frame = self.view.bounds;
[self.view addSubview:self.cameraView];
}
#pragma mark - 按钮点击事件
-(void)cameraViewBtnClickedWithTag:(NSInteger)tag{
switch (tag) {
case 0:{//返回按钮点击事件
[self.navigationController popViewControllerAnimated:YES];
}break;
case 1:{//电灯按钮点击事件
}break;
case 2:{//拍照按钮点击事件
[self shutterCamera];
}break;
default:
break;
}
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
self.navigationController.navigationBar.hidden = NO;
[UIApplication sharedApplication].statusBarHidden = NO;
}
//AVMediaTypeVideo设置
- (void)customCamera{
self.view.backgroundColor = [UIColor whiteColor];
//使用AVMediaTypeVideo 指明self.device代表视频,默认使用后置摄像头进行初始化
self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//使用设备初始化输入
self.input = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:nil];
//生成输出对象
self.output = [[AVCaptureMetadataOutput alloc]init];
self.ImageOutPut = [[AVCaptureStillImageOutput alloc] init];
//生成会话,用来结合输入输出
self.session = [[AVCaptureSession alloc]init];
if ([self.session canSetSessionPreset:AVCaptureSessionPreset1280x720]) {
self.session.sessionPreset = AVCaptureSessionPreset1280x720;
}
if ([self.session canAddInput:self.input]) {
[self.session addInput:self.input];
}
if ([self.session canAddOutput:self.ImageOutPut]) {
[self.session addOutput:self.ImageOutPut];
}
//使用self.session,初始化预览层,self.session负责驱动input进行信息的采集,layer负责把图像渲染显示
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
self.previewLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:self.previewLayer];
//开始启动
[self.session startRunning];
if ([_device lockForConfiguration:nil]) {
if ([_device isFlashModeSupported:AVCaptureFlashModeAuto]) {
[_device setFlashMode:AVCaptureFlashModeAuto];
}
//自动白平衡
if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
[_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
}
[_device unlockForConfiguration];
}
}
- (void)FlashOn{
if ([_device lockForConfiguration:nil]) {
if (_isflashOn) {
if ([_device isFlashModeSupported:AVCaptureFlashModeOff]) {
[_device setFlashMode:AVCaptureFlashModeOff];
_isflashOn = NO;
// [_flashButton setTitle:@"闪光灯关" forState:UIControlStateNormal];
}
}else{
if ([_device isFlashModeSupported:AVCaptureFlashModeOn]) {
[_device setFlashMode:AVCaptureFlashModeOn];
_isflashOn = YES;
// [_flashButton setTitle:@"闪光灯开" forState:UIControlStateNormal];
}
}
[_device unlockForConfiguration];
}
}
- (void)changeCamera{
NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
if (cameraCount > 1) {
NSError *error;
CATransition *animation = [CATransition animation];
animation.duration = .5f;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.type = @"oglFlip";
AVCaptureDevice *newCamera = nil;
AVCaptureDeviceInput *newInput = nil;
AVCaptureDevicePosition position = [[_input device] position];
if (position == AVCaptureDevicePositionFront){
newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
animation.subtype = kCATransitionFromLeft;
}
else {
newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
animation.subtype = kCATransitionFromRight;
}
newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
[self.previewLayer addAnimation:animation forKey:nil];
if (newInput != nil) {
[self.session beginConfiguration];
[self.session removeInput:_input];
if ([self.session canAddInput:newInput]) {
[self.session addInput:newInput];
self.input = newInput;
} else {
[self.session addInput:self.input];
}
[self.session commitConfiguration];
} else if (error) {
NSLog(@"toggle carema failed, error = %@", error);
}
}
}
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for ( AVCaptureDevice *device in devices )
if ( device.position == position ) return device;
return nil;
}
- (void)focusGesture:(UITapGestureRecognizer*)gesture{
CGPoint point = [gesture locationInView:gesture.view];
[self focusAtPoint:point];
}
- (void)focusAtPoint:(CGPoint)point{
CGSize size = self.view.bounds.size;
CGPoint focusPoint = CGPointMake( point.y /size.height ,1-point.x/size.width );
NSError *error;
if ([self.device lockForConfiguration:&error]) {
if ([self.device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
[self.device setFocusPointOfInterest:focusPoint];
[self.device setFocusMode:AVCaptureFocusModeAutoFocus];
}
if ([self.device isExposureModeSupported:AVCaptureExposureModeAutoExpose ]) {
[self.device setExposurePointOfInterest:focusPoint];
[self.device setExposureMode:AVCaptureExposureModeAutoExpose];
}
[self.device unlockForConfiguration];
// _focusView.center = point;
// _focusView.hidden = NO;
[UIView animateWithDuration:0.3 animations:^{
// _focusView.transform = CGAffineTransformMakeScale(1.25, 1.25);
}completion:^(BOOL finished) {
[UIView animateWithDuration:0.5 animations:^{
// _focusView.transform = CGAffineTransformIdentity;
} completion:^(BOOL finished) {
// _focusView.hidden = YES;
}];
}];
}
}
#pragma mark - 截取照片
- (void) shutterCamera{
AVCaptureConnection * videoConnection = [self.ImageOutPut connectionWithMediaType:AVMediaTypeVideo];
if (!videoConnection) {
NSLog(@"take photo failed!");
[SVProgressHUD showErrorWithStatus:@"拍照失败,稍后重试!" duration:2.0];
[self.navigationController popViewControllerAnimated:YES];
return;
}
[self.ImageOutPut captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
if (imageDataSampleBuffer == NULL) {
return;
}
NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *imageResult = [UIImage imageWithData:imageData];
[self.session stopRunning];
//改变该图片的方向
self.image = [UIImage imageWithCGImage:imageResult.CGImage
scale:imageResult.scale
orientation:UIImageOrientationUp];
if (self.image) {
if (self.delegate && [self.delegate respondsToSelector:@selector(popControllerWithImage:)]) {
[self.delegate popControllerWithImage:self.image];
[self.navigationController popViewControllerAnimated:YES];
}
}
// [self saveImageToPhotoAlbum:self.image];
// self.imageView = [[UIImageView alloc]initWithFrame:self.previewLayer.frame];
// [self.view insertSubview:_imageView belowSubview:_PhotoButton];
// self.imageView.layer.masksToBounds = YES;
// self.imageView.image = _image;
NSLog(@"image size = %@",NSStringFromCGSize(self.image.size));
}];
}
#pragma - 保存至相册
- (void)saveImageToPhotoAlbum:(UIImage*)savedImage{
UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
// 指定回调方法
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo{
NSString *msg = nil ;
if(error != NULL){
msg = @"保存图片失败" ;
}else{
msg = @"保存图片成功" ;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存图片结果提示"
message:msg
delegate:self
cancelButtonTitle:@"确定"
otherButtonTitles:nil];
[alert show];
}
//取消按钮点击事件
-(void)cancle{
[self.imageView removeFromSuperview];
[self.session startRunning];
}
#pragma mark - 检查相机权限
- (BOOL)canUserCamear{
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (authStatus == AVAuthorizationStatusDenied) {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"请打开相机权限" message:@"设置-隐私-相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
alertView.tag = 100;
[alertView show];
return NO;
}
else{
return YES;
}
return YES;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0 && alertView.tag == 100) {
NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
}
}
@end
WYPCustomCameraView:
//
// WYPCustomCameraView.h
// RockUnion
//
// Created by 王彦平 on 2021/12/29.
// Copyright © 2021 王彦平. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, WYPCameraActionType) {
WYPCameraFrontIDCardPicture = 0,//身份证正面
WYPCameraReverseIDCardPicture,//身份证反面
WYPCameraBankCardPicture,//银行卡
};
typedef void(^TypeBtnClicedBlock)(NSInteger tag);
@interface WYPCustomCameraView : UIView
@property (nonatomic, strong) TypeBtnClicedBlock btnBlock;
@property (nonatomic, assign) WYPCameraActionType cameraType;
+(instancetype)WYPCustomCameraView;
@end
NS_ASSUME_NONNULL_END
//
// WYPCustomCameraView.m
// RockUnion
//
// Created by 王彦平 on 2021/12/29.
// Copyright © 2021 王彦平. All rights reserved.
//
#import "WYPCustomCameraView.h"
#import <AVFoundation/AVFoundation.h>
@interface WYPCustomCameraView()
@property (weak, nonatomic) IBOutlet UILabel *cardLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *cardLabelRightMargin;
@property (weak, nonatomic) IBOutlet UILabel *lightLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lightLabelRightMargin;
@property (weak, nonatomic) IBOutlet UIView *maskView;
@property (weak, nonatomic) IBOutlet UIImageView *sqImgView;
@property (nonatomic, strong)UIImageView *preView;
//捕获设备,通常是前置摄像头,后置摄像头,麦克风(音频输入)
@property(nonatomic)AVCaptureDevice *device;
@property (weak, nonatomic) IBOutlet UIImageView *embleImgView;//国徽图标
@property (weak, nonatomic) IBOutlet UIImageView *portraitImgView;//头像图标
@end
@implementation WYPCustomCameraView
+(instancetype)WYPCustomCameraView{
return [[[NSBundle mainBundle] loadNibNamed:@"WYPCustomCameraView" owner:nil options:nil]lastObject];
}
-(void)awakeFromNib{
[super awakeFromNib];
[self setUI];
[self customCamera];
}
//设置UI
-(void)setUI{
self.backgroundColor = [UIColor clearColor];
CGAffineTransform transform= CGAffineTransformRotate(self.cardLabel.transform, M_PI_2);
self.cardLabel.transform = transform;
self.cardLabelRightMargin.constant = -100;
CGAffineTransform transform1 = CGAffineTransformRotate(self.lightLabel.transform, M_PI_2);
self.lightLabel.transform = transform1;
self.lightLabelRightMargin.constant = -15;
self.maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
self.maskView.frame = CGRectMake(0,0, SCREEN_WIDTH, SCREEN_HEIGHT);
UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.maskView.bounds];
// 创建矩形
CGFloat circlePathWidth = SCREEN_WIDTH - 42.0 - 44.0;
CGFloat circlePathHeight = circlePathWidth * 445.0/289.0;
CGRect circlePathRect = CGRectMake(42.0, (SCREEN_HEIGHT - circlePathHeight)*0.5, circlePathWidth, circlePathHeight);
UIBezierPath *circlePath = [UIBezierPath bezierPathWithRect:circlePathRect];
[path appendPath:circlePath];
CAShapeLayer *shaperLayer = [CAShapeLayer layer];
shaperLayer.frame = self.maskView.bounds;
shaperLayer.fillColor = [UIColor colorWithHexString:@"000000" alpha:0.3].CGColor;
// 设置填充规则
shaperLayer.fillRule = kCAFillRuleEvenOdd;
shaperLayer.path = path.CGPath;
[self.maskView.layer addSublayer: shaperLayer];
}
- (void)customCamera{
//使用AVMediaTypeVideo 指明self.device代表视频,默认使用后置摄像头进行初始化
self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
}
#pragma mark - 按钮点击事件
//返回按钮点击事件
- (IBAction)backBtnClicked:(UIButton *)sender {
if (self.btnBlock) {
self.btnBlock(sender.tag - 10);
}
}
//电灯按钮点击事件
- (IBAction)lightBtnClicked:(UIButton *)sender {
if (self.btnBlock) {
self.btnBlock(sender.tag - 10);
}
// [self flashOn:sender.selected];
[self turnTorchOn:sender];
}
//拍照按钮点击事件
- (IBAction)cameraBtnClicked:(UIButton *)sender {
if (self.btnBlock) {
self.btnBlock(sender.tag - 10);
}
}
//闪光灯开关
- (void)flashOn:(BOOL)isflashOn{
if (!isflashOn) {
self.lightLabel.text = @"闪光灯关";
}else{
self.lightLabel.text = @"闪光灯开";
}
}
//手电筒
-(void)turnTorchOn: (UIButton *) sender{
sender.selected = !sender.selected;
if (!sender.selected) {
self.lightLabel.text = @"轻触关闭";
}else{
self.lightLabel.text = @"轻触照亮";
}
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass !=nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
if (sender.selected) {
[device setTorchMode:AVCaptureTorchModeOn];
// [device setFlashMode:AVCaptureFlashModeOn];
} else {
[device setTorchMode:AVCaptureTorchModeOff];
// [device setFlashMode:AVCaptureFlashModeOff];
}
[device unlockForConfiguration];
}else{
NSLog(@"初始化失败");
}
}else{
NSLog(@"没有闪光设备");
}
}
//设置拍照类型
-(void)setCameraType:(WYPCameraActionType)cameraType{
_cameraType = cameraType;
switch (cameraType) {
case WYPCameraFrontIDCardPicture:{//身份证正面
self.portraitImgView.hidden = NO;
self.embleImgView.hidden = YES;
}break;
case WYPCameraReverseIDCardPicture:{//身份证反面
self.portraitImgView.hidden = YES;
self.embleImgView.hidden = NO;
}break;
default:{//银行卡
self.portraitImgView.hidden = YES;
self.embleImgView.hidden = YES;
}break;
}
}
@end
调用:
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
[actionSheet addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// self.imagePickerPhotoVC.sourceType = UIImagePickerControllerSourceTypeCamera;
// self.imagePickerPhotoVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
// [self presentViewController:self.imagePickerPhotoVC animated:YES completion:nil];
WYPCustomCameraVC *cameraVC = [[WYPCustomCameraVC alloc]init];
cameraVC.hidesBottomBarWhenPushed = YES;
cameraVC.delegate = self;
[self.navigationController pushViewController:cameraVC animated:YES];
if(self.transitionImgView.tag == 100){//身份证正面
cameraVC.cameraType = WYPCameraFrontIDCardPicture;
}else if (self.transitionImgView.tag == 200){//身份证反面
cameraVC.cameraType = WYPCameraReverseIDCardPicture;
}else if (self.transitionImgView.tag == 300){//银行卡照
cameraVC.cameraType = WYPCameraBankCardPicture;
}
}]];
}
[actionSheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
[self setStatusBarBackgroundColor:[UIColor clearColor]];
}]];
2.方法二:WYPImagePickerController 继承UIImagePickerController:
//
// WYPImagePickerController.h
// RockUnion
//
// Created by 王彦平 on 2021/12/29.
// Copyright © 2021 王彦平. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface WYPImagePickerController : UIImagePickerController
@end
NS_ASSUME_NONNULL_END
//
// WYPImagePickerController.m
// RockUnion
//
// Created by 王彦平 on 2021/12/29.
// Copyright © 2021 王彦平. All rights reserved.
//
#import "WYPImagePickerController.h"
#import "WYPImageView.h"
#import "WYPCustomCameraView.h"
@interface WYPImagePickerController ()
@property (nonatomic, strong) WYPCustomCameraView *cameraView;
@end
@implementation WYPImagePickerController
#pragma mark - lazy
-(WYPCustomCameraView *)cameraView{
if (!_cameraView) {
_cameraView = [WYPCustomCameraView WYPCustomCameraView];
WS(weakSelf);
_cameraView.btnBlock = ^(NSInteger tag) {
[weakSelf cameraViewBtnClickedWithTag:tag];
};
}
return _cameraView;
}
- (void)viewDidLoad {
[super viewDidLoad];
WYPImageView *imageView = [[WYPImageView alloc]initWithFrame:self.view.bounds];
self.cameraView.frame = imageView.bounds;
[imageView addSubview:self.cameraView];
self.cameraOverlayView = imageView;
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self setNav];
}
//设置状态栏
-(void)setNav{
// 设置状态栏
[Tools setStatusBarBackgroundColor:[UIColor clearColor]];
self.navigationController.navigationBar.hidden = YES;
[UIApplication sharedApplication].statusBarHidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
self.navigationController.navigationBar.hidden = NO;
[UIApplication sharedApplication].statusBarHidden = NO;
}
#pragma mark - 按钮点击事件
-(void)cameraViewBtnClickedWithTag:(NSInteger)tag{
switch (tag) {
case 0:{//返回按钮点击事件
[self dismissViewControllerAnimated:YES completion:nil];
}break;
case 1:{//电灯按钮点击事件
[self flashModeOn];
}break;
case 2:{//拍照按钮点击事件
[self takePicture];
}break;
default:
break;
}
}
//闪光灯
-(void)flashModeOn{
if (self.cameraFlashMode == UIImagePickerControllerCameraFlashModeAuto) {
self.cameraFlashMode = UIImagePickerControllerCameraFlashModeOn;
}else{
self.cameraFlashMode = UIImagePickerControllerCameraFlashModeOff;
}
}
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// NSString *oldKey = self.item.itemKey;
//
// // Did the item already have an image?
// if (oldKey) {
// // Delete the old image
// [[BNRImageStore sharedStore] deleteImageForKey:oldKey];
// }
//
// UIImage *image;
// // Get picked image from info dictionary
// if (info[UIImagePickerControllerEditedImage]) {
// image =info[UIImagePickerControllerEditedImage];
// }
// else
// {
// image = info[UIImagePickerControllerOriginalImage];
// }
//
//
//
//
// // Store the image in the BNRImageStore for this key
// [[BNRImageStore sharedStore] setImage:image forKey:self.item.itemKey];
//
// // Put that image onto the screen in our image view
// self.imageView.image = image;
// Take image picker off the screen -
// you must call this dismiss method
[self dismissViewControllerAnimated:YES completion:NULL];
}
@end
//
//
// WYPCustomCameraView.h
// RockUnion
//
// Created by 王彦平 on 2021/12/29.
// Copyright © 2021 王彦平. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, WYPCameraActionType) {
WYPCameraFrontIDCardPicture = 0,//身份证正面
WYPCameraReverseIDCardPicture,//身份证反面
WYPCameraBankCardPicture,//银行卡
};
typedef void(^TypeBtnClicedBlock)(NSInteger tag);
@interface WYPCustomCameraView : UIView
@property (nonatomic, strong) TypeBtnClicedBlock btnBlock;
@property (nonatomic, assign) WYPCameraActionType cameraType;
+(instancetype)WYPCustomCameraView;
@end
NS_ASSUME_NONNULL_END
//
// WYPCustomCameraView.m
// RockUnion
//
// Created by 王彦平 on 2021/12/29.
// Copyright © 2021 王彦平. All rights reserved.
//
#import "WYPCustomCameraView.h"
#import <AVFoundation/AVFoundation.h>
@interface WYPCustomCameraView()
@property (weak, nonatomic) IBOutlet UILabel *cardLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *cardLabelRightMargin;
@property (weak, nonatomic) IBOutlet UILabel *lightLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lightLabelRightMargin;
@property (weak, nonatomic) IBOutlet UIView *maskView;
@property (weak, nonatomic) IBOutlet UIImageView *sqImgView;
@property (nonatomic, strong)UIImageView *preView;
//捕获设备,通常是前置摄像头,后置摄像头,麦克风(音频输入)
@property(nonatomic)AVCaptureDevice *device;
@property (weak, nonatomic) IBOutlet UIImageView *embleImgView;//国徽图标
@property (weak, nonatomic) IBOutlet UIImageView *portraitImgView;//头像图标
@end
@implementation WYPCustomCameraView
+(instancetype)WYPCustomCameraView{
return [[[NSBundle mainBundle] loadNibNamed:@"WYPCustomCameraView" owner:nil options:nil]lastObject];
}
-(void)awakeFromNib{
[super awakeFromNib];
[self setUI];
[self customCamera];
}
//设置UI
-(void)setUI{
self.backgroundColor = [UIColor clearColor];
CGAffineTransform transform= CGAffineTransformRotate(self.cardLabel.transform, M_PI_2);
self.cardLabel.transform = transform;
self.cardLabelRightMargin.constant = -100;
CGAffineTransform transform1 = CGAffineTransformRotate(self.lightLabel.transform, M_PI_2);
self.lightLabel.transform = transform1;
self.lightLabelRightMargin.constant = -15;
self.maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
self.maskView.frame = CGRectMake(0,0, SCREEN_WIDTH, SCREEN_HEIGHT);
UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.maskView.bounds];
// 创建矩形
CGFloat circlePathWidth = SCREEN_WIDTH - 42.0 - 44.0;
CGFloat circlePathHeight = circlePathWidth * 445.0/289.0;
CGRect circlePathRect = CGRectMake(42.0, (SCREEN_HEIGHT - circlePathHeight)*0.5, circlePathWidth, circlePathHeight);
UIBezierPath *circlePath = [UIBezierPath bezierPathWithRect:circlePathRect];
[path appendPath:circlePath];
CAShapeLayer *shaperLayer = [CAShapeLayer layer];
shaperLayer.frame = self.maskView.bounds;
shaperLayer.fillColor = [UIColor colorWithHexString:@"000000" alpha:0.3].CGColor;
// 设置填充规则
shaperLayer.fillRule = kCAFillRuleEvenOdd;
shaperLayer.path = path.CGPath;
[self.maskView.layer addSublayer: shaperLayer];
}
- (void)customCamera{
//使用AVMediaTypeVideo 指明self.device代表视频,默认使用后置摄像头进行初始化
self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
}
#pragma mark - 按钮点击事件
//返回按钮点击事件
- (IBAction)backBtnClicked:(UIButton *)sender {
if (self.btnBlock) {
self.btnBlock(sender.tag - 10);
}
}
//电灯按钮点击事件
- (IBAction)lightBtnClicked:(UIButton *)sender {
if (self.btnBlock) {
self.btnBlock(sender.tag - 10);
}
// [self flashOn:sender.selected];
[self turnTorchOn:sender];
}
//拍照按钮点击事件
- (IBAction)cameraBtnClicked:(UIButton *)sender {
if (self.btnBlock) {
self.btnBlock(sender.tag - 10);
}
}
//闪光灯开关
- (void)flashOn:(BOOL)isflashOn{
if (!isflashOn) {
self.lightLabel.text = @"闪光灯关";
}else{
self.lightLabel.text = @"闪光灯开";
}
}
//手电筒
-(void)turnTorchOn: (UIButton *) sender{
sender.selected = !sender.selected;
if (!sender.selected) {
self.lightLabel.text = @"闪光灯关";
}else{
self.lightLabel.text = @"闪光灯开";
}
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass !=nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
if (sender.selected) {
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
} else {
[device setTorchMode:AVCaptureTorchModeOff];
[device setFlashMode:AVCaptureFlashModeOff];
}
[device unlockForConfiguration];
}else{
NSLog(@"初始化失败");
}
}else{
NSLog(@"没有闪光设备");
}
}
//设置拍照类型
-(void)setCameraType:(WYPCameraActionType)cameraType{
_cameraType = cameraType;
switch (cameraType) {
case WYPCameraFrontIDCardPicture:{//身份证正面
self.portraitImgView.hidden = NO;
self.embleImgView.hidden = YES;
}break;
case WYPCameraReverseIDCardPicture:{//身份证反面
self.portraitImgView.hidden = YES;
self.embleImgView.hidden = NO;
}break;
default:{//银行卡
self.portraitImgView.hidden = YES;
self.embleImgView.hidden = YES;
}break;
}
}
@end
最后
以上就是拉长巨人为你收集整理的iOS自定义相机的全部内容,希望文章能够帮你解决iOS自定义相机所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复