iOS自定义相机
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;@endNS_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.CGImagescale:imageResult.scaleorientation: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:msgdelegate:selfcancelButtonTitle:@"確定"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];}} }@endWYPCustomCameraView:
// // WYPCustomCameraView.h // RockUnion // // Created by 王彥平 on 2021/12/29. // Copyright ? 2021 王彥平. All rights reserved. //#import <UIKit/UIKit.h>NS_ASSUME_NONNULL_BEGINtypedef 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;@endNS_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@endNS_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_BEGINtypedef 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;@endNS_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總結
- 上一篇: PyQt5GUI快速编程学习
- 下一篇: 论文排版神器——Texlive + Te