我是靠谱客的博主 拉长巨人,这篇文章主要介绍iOS自定义相机,现在分享给大家,希望可以做个参考。

1.方法一:截屏:

WYPCustomCameraVC:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// // 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:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// // 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

调用:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
// // 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

//

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// // 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自定义相机内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(95)

评论列表共有 0 条评论

立即
投稿
返回
顶部