您好,登錄后才能下訂單哦!
本篇文章為大家展示了如何用AVFoundation框架實現相機拍照和錄制視頻,代碼簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
這里是Demo
首先聲明以下對象:
#import "CustomeCameraViewController.h" #import <AVFoundation/AVFoundation.h> #import <AssetsLibrary/AssetsLibrary.h> @interface CustomeCameraViewController ()<AVCaptureFileOutputRecordingDelegate> { // AVCaptureSession對象來執(zhí)行輸入設備和輸出設備之間的數據傳遞 AVCaptureSession *iSession; //當前設備 AVCaptureDevice *iDevice; //輸入設備 AVCaptureDeviceInput *iDeviceInput; //照片輸出流 AVCaptureStillImageOutput *iStillImageOutput; //預覽圖層 AVCaptureVideoPreviewLayer *iPreviewLayer; }
初始化各對象:
-(void)viewDidLoad { [super viewDidLoad]; //點擊屏幕對焦 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]; ////輸出設置。AVVideoCodecJPEG 輸出jpeg格式圖片 iStillImageOutput = [[AVCaptureStillImageOutput alloc]init]; NSDictionary *outputDic = [NSDictionary dictionaryWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil nil]; [iStillImageOutput setOutputSettings:outputDic]; //更改這個設備設置的時候必須先鎖定設備,修改完后再解鎖,否則崩潰 [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]; } //初始化預覽圖層 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]; }
點擊按鈕拍照:
//拍照 -(void)takePictures{ AVCaptureConnection *connection = [iStillImageOutput connectionWithMediaType:AVMediaTypeVideo]; if (!connection) { NSLog(@"失敗"); return; } //設置焦距 [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即為拍照所得圖片.
設置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; } }
設置閃光燈:
- (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]; } }
點擊屏幕對焦:
//點擊屏幕對焦 -(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; }]; }]; }
關于視頻錄制可以在Demo中查看。
上述內容就是如何用AVFoundation框架實現相機拍照和錄制視頻,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。