本篇文章為大家展示了如何用AVFoundation框架實(shí)現(xiàn)相機(jī)拍照和錄制視頻,代碼簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
創(chuàng)新互聯(lián)建站-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比金林網(wǎng)站開(kāi)發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫(kù),直接使用。一站式金林網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋金林地區(qū)。費(fèi)用合理售后完善,10余年實(shí)體公司更值得信賴。
這里是Demo
首先聲明以下對(duì)象:
#import "CustomeCameraViewController.h" #import#import @interface CustomeCameraViewController () { // AVCaptureSession對(duì)象來(lái)執(zhí)行輸入設(shè)備和輸出設(shè)備之間的數(shù)據(jù)傳遞 AVCaptureSession *iSession; //當(dāng)前設(shè)備 AVCaptureDevice *iDevice; //輸入設(shè)備 AVCaptureDeviceInput *iDeviceInput; //照片輸出流 AVCaptureStillImageOutput *iStillImageOutput; //預(yù)覽圖層 AVCaptureVideoPreviewLayer *iPreviewLayer; }
初始化各對(duì)象:
-(void)viewDidLoad { [super viewDidLoad]; //點(diǎn)擊屏幕對(duì)焦 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(focusTap:)]; [self.view addGestureRecognizer:tap]; iSession = [[AVCaptureSession alloc]init]; NSArray *deviceArray = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; for (AVCaptureDevice *device in deviceArray) { //AVCaptureDevicePositionBack 后置攝像頭 //AVCaptureDevicePositionFront 前置攝像頭 if (device.position == AVCaptureDevicePositionBack) { iDevice = device; } } iSession.sessionPreset = [self getSessionPresetForDevice:iDevice]; iDeviceInput = [[AVCaptureDeviceInput alloc]initWithDevice:iDevice error:nil]; ////輸出設(shè)置。AVVideoCodecJPEG 輸出jpeg格式圖片 iStillImageOutput = [[AVCaptureStillImageOutput alloc]init]; NSDictionary *outputDic = [NSDictionary dictionaryWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil nil]; [iStillImageOutput setOutputSettings:outputDic]; //更改這個(gè)設(shè)備設(shè)置的時(shí)候必須先鎖定設(shè)備,修改完后再解鎖,否則崩潰 [iDevice lockForConfiguration:nil]; if ([iDevice isFlashModeSupported:AVCaptureFlashModeOff]) { [iDevice setFlashMode:AVCaptureFlashModeOff]; } if ([iDevice isFocusModeSupported:AVCaptureFocusModeAutoFocus]) { [iDevice setFocusMode:AVCaptureFocusModeAutoFocus]; } if ([iDevice isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) { [iDevice setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance]; } [iDevice unlockForConfiguration]; if ([iSession canAddInput:iDeviceInput]) { [iSession addInput:iDeviceInput]; } if ([iSession canAddOutput:iStillImageOutput]) { [iSession addOutput:iStillImageOutput]; } if ([iSession canAddOutput:iVideoOutput]) { [iSession addOutput:iVideoOutput]; } //初始化預(yù)覽圖層 iPreviewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:iSession]; [iPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill]; iPreviewLayer.frame = CGRectMake(0, 60, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-160); [self.iCameraView.layer addSublayer:iPreviewLayer]; [iSession startRunning]; }
點(diǎn)擊按鈕拍照:
//拍照 -(void)takePictures{ AVCaptureConnection *connection = [iStillImageOutput connectionWithMediaType:AVMediaTypeVideo]; if (!connection) { NSLog(@"失敗"); return; } //設(shè)置焦距 [connection setVideoScaleAndCropFactor:1]; [iStillImageOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) { if (imageDataSampleBuffer==NULL) { NSLog(@"NUll"); return ; } NSData *data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer]; UIImage *image = [UIImage imageWithData:data]; }]; }
image即為拍照所得圖片.
設(shè)置session的AVCaptureSessionPreset屬性
-(NSString *)getSessionPresetForDevice:(AVCaptureDevice *)device{ if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset3840x2160]) { return AVCaptureSessionPreset3840x2160; } else if([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset1920x1080]){ return AVCaptureSessionPreset1920x1080; } else if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset1280x720]){ return AVCaptureSessionPreset1280x720; } else if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset640x480]){ return AVCaptureSessionPreset640x480; } else if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset352x288]){ return AVCaptureSessionPreset352x288; } else if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPresetHigh]){ return AVCaptureSessionPresetHigh; } else if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPresetMedium]){ return AVCaptureSessionPresetMedium; } else{ return AVCaptureSessionPresetLow; } }
設(shè)置閃光燈:
- (IBAction)iFlashBtn:(id)sender { [iDevice lockForConfiguration:nil]; if (iDevice.flashMode == AVCaptureFlashModeOff) { if ([iDevice isFlashModeSupported:AVCaptureFlashModeOn]) { [iDevice setFlashMode:AVCaptureFlashModeOn]; [self.iFlashBtn setBackgroundImage:[UIImage imageNamed:@"flashBtn"] forState:UIControlStateNormal]; } } else if (iDevice.flashMode == AVCaptureFlashModeOn){ if ([iDevice isFlashModeSupported:AVCaptureFlashModeOff]) { [iDevice setFlashMode:AVCaptureFlashModeOff]; [self.iFlashBtn setBackgroundImage:[UIImage imageNamed:@"flashOffBtn"] forState:UIControlStateNormal]; } } [iDevice unlockForConfiguration]; }
切換前置攝像頭與后置攝像頭:
- (IBAction)iChangeBtn:(id)sender { NSArray *array = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; AVCaptureDevice *newDevice = nil; AVCaptureDeviceInput *newDeviceInput = nil; CATransition *animation = [CATransition animation]; animation.duration = 0.5f; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; animation.type = @"oglFlip"; if (iDevice.position == AVCaptureDevicePositionBack) { animation.subtype = kCATransitionFromLeft; for (AVCaptureDevice *device in array) { if (device.position == AVCaptureDevicePositionFront) { newDevice = device; } } } else if (iDevice.position == AVCaptureDevicePositionFront){ animation.subtype = kCATransitionFromRight; for (AVCaptureDevice *device in array) { if (device.position == AVCaptureDevicePositionBack) { newDevice = device; } } } newDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:newDevice error:nil]; [iPreviewLayer addAnimation:animation forKey:nil]; if (newDeviceInput!=nil) { [iSession beginConfiguration]; [iSession removeInput:iDeviceInput]; iSession.sessionPreset = [self getSessionPresetForDevice:newDevice]; if ([iSession canAddInput:newDeviceInput]) { [iSession addInput:newDeviceInput]; iDeviceInput = newDeviceInput; iDevice = newDevice; } else { [iSession addInput:iDeviceInput]; } [iSession commitConfiguration]; } }
點(diǎn)擊屏幕對(duì)焦:
//點(diǎn)擊屏幕對(duì)焦 -(void)focusTap:(UIGestureRecognizer *)tap{ CGPoint tapPoint = [tap locationInView:self.view]; float Y = tapPoint.y; if (Y<60 || Y>([UIScreen mainScreen].bounds.size.height-100)) { return; } [iDevice lockForConfiguration:nil]; if ([iDevice isFocusModeSupported:AVCaptureFocusModeAutoFocus]) { [iDevice setFocusPointOfInterest:CGPointMake(tapPoint.x/self.view.frame.origin.x, tapPoint.y/self.view.frame.origin.y)]; [iDevice setFocusMode:AVCaptureFocusModeAutoFocus]; } [iDevice unlockForConfiguration]; self.iFocusImgView.center = tapPoint; self.iFocusImgView.hidden = NO; [UIView animateWithDuration:0.3 animations:^{ self.iFocusImgView.transform = CGAffineTransformMakeScale(1.25, 1.25); }completion:^(BOOL finished) { [UIView animateWithDuration:0.5 animations:^{ self.iFocusImgView.transform = CGAffineTransformIdentity; } completion:^(BOOL finished) { self.iFocusImgView.hidden = YES; }]; }]; }
關(guān)于視頻錄制可以在Demo中查看。
上述內(nèi)容就是如何用AVFoundation框架實(shí)現(xiàn)相機(jī)拍照和錄制視頻,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。