最近也是因?yàn)轫?xiàng)目需要開發(fā)一個(gè)很奇葩的功能曼玩,接觸了相機(jī)功能扛伍,也接觸了這個(gè)相機(jī)功能筷畦。
首先,iOS相機(jī)功能分兩種實(shí)現(xiàn)方式刺洒,一種是系統(tǒng)的UIImagePickerController鳖宾,一種是自定義的AVCaptureSession,我自己剛開始的時(shí)候一直以為UIImagePickerController是自己寫的類逆航。鼎文。。
另外因俐,使用相機(jī)前拇惋,要獲取相機(jī)的使用權(quán)限,這個(gè)網(wǎng)上好的大把抹剩,就不寫了撑帖。
一、UIImagePickerController
1.跳轉(zhuǎn)Controller實(shí)現(xiàn)兩個(gè)協(xié)議UIImagePickerControllerDelegate和UINavigationControllerDelegate
2.實(shí)例化澳眷,實(shí)現(xiàn)協(xié)議跳轉(zhuǎn)
UIImagePickerController*pick = [[UIImagePickerControlleralloc]init];
pick.delegate=self;
pick.sourceType=UIImagePickerControllerSourceTypeCamera;
//想要相機(jī)全屏胡嘿,用這個(gè)showsCameraControls設(shè)置成NO后相機(jī)的UI會(huì)被隱藏了,但是底部的工具欄會(huì)留下一個(gè)個(gè)黑塊钳踊,解決辦法是一個(gè)取巧的辦法灶平,CGAffineTransformMakeScale
pick.showsCameraControls=NO;
//但是這樣就是放大的效果,有好有壞吧箍土,不行就只能用自定義的了
pick.cameraViewTransform=CGAffineTransformMakeScale(2,2);
[selfpresentViewController:pickanimated:YEScompletion:^{
}];
還有一種相機(jī)的實(shí)現(xiàn)方式
二、AVCaptureSession
1罐监,導(dǎo)入AVfounation包
2.實(shí)例化
//1.創(chuàng)建媒體管理會(huì)話
AVCaptureSession*session = [[AVCaptureSessionalloc]init];
//判斷分辨率是否支持1280*720吴藻,支持就設(shè)置為1280*720
if( [sessioncanSetSessionPreset:AVCaptureSessionPreset1280x720] ) {
session.sessionPreset=AVCaptureSessionPreset1280x720;
}
//2.獲取后置攝像頭設(shè)備對(duì)象
AVCaptureDevice*device =nil;
NSArray*cameras = [AVCaptureDevicedevicesWithMediaType:AVMediaTypeVideo];
for(AVCaptureDevice*cameraincameras) {
if(camera.position==AVCaptureDevicePositionBack) {//取得后置攝像頭
device = camera;
}
}
if(!device) {
NSLog(@"取得后置攝像頭錯(cuò)誤");
return;
}
//3.創(chuàng)建輸入數(shù)據(jù)對(duì)象
NSError*error =nil;
AVCaptureDeviceInput*captureInput = [[AVCaptureDeviceInputalloc]initWithDevice:device
error:&error];
if(error) {
NSLog(@"創(chuàng)建輸入數(shù)據(jù)對(duì)象錯(cuò)誤");
return;
}
//4.創(chuàng)建輸出數(shù)據(jù)對(duì)象
AVCaptureStillImageOutput*imageOutput = [[AVCaptureStillImageOutputalloc]init];
NSDictionary*setting =@{AVVideoCodecKey:AVVideoCodecJPEG};
[imageOutputsetOutputSettings:setting];
//5.添加輸入數(shù)據(jù)對(duì)象和輸出對(duì)象到會(huì)話中
if([sessioncanAddInput:captureInput]) {
[sessionaddInput:captureInput];
}
if([sessioncanAddOutput:imageOutput]) {
[sessionaddOutput:imageOutput];
}
//6.創(chuàng)建視頻預(yù)覽圖層
AVCaptureVideoPreviewLayer*videoLayer =
[[AVCaptureVideoPreviewLayeralloc]initWithSession:session];
self.view.layer.masksToBounds=YES;
videoLayer.frame=self.view.bounds;
videoLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;
[self.view.layeraddSublayer:videoLayer];
//這里需要設(shè)置相機(jī)開始捕捉畫面
[sessionstartRunning];//開始捕捉