- (void)viewDidLoad {
[super viewDidLoad];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 100, 100);
btn.center = self.view.center;
[btn setTitle:@"拍照" forState:UIControlStateNormal];
btn.backgroundColor = [UIColor orangeColor];
[btn addTarget:self action:@selector(clickAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
//会话
_sesion = [[AVCaptureSession alloc] init];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
[_sesion setSessionPreset:AVCaptureSessionPresetPhoto];
}
AVCaptureDevice *device = [self cameraWithPosition: AVCaptureDevicePositionBack];
//输入源
_input = [[AVCaptureDeviceInput alloc] initWithDevice:device error:nil];
if ([_sesion canAddInput:_input]) {
[_sesion addInput:_input];
}
//输出源
_photoOut = [AVCaptureStillImageOutput new];
if ([_sesion canAddOutput:_photoOut]) {
[_sesion addOutput:_photoOut];
}
_previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_sesion];
_previewLayer.bounds = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
[self.view.layer addSublayer:_previewLayer];
[_sesion startRunning];
}
- (void)clickAction {
AVCaptureConnection *connect = [_photoOut connectionWithMediaType:AVMediaTypeVideo];
[self.photoOut captureStillImageAsynchronouslyFromConnection:connect completionHandler:^(CMSampleBufferRef _Nullable imageDataSampleBuffer, NSError * _Nullable error) {
NSData *data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image = [UIImage imageWithData:data];
UIImageView *img = [[UIImageView alloc] initWithImage:image];
img.frame = CGRectMake(20, 20, 100, 100);
[self.view addSubview:img];
}];
}
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for ( AVCaptureDevice *device in devices ){
if ( device.position == position )
return device;
}
return nil;
}
网友评论