IOS自定義相機<AVFoundation>

//捕獲設備,通常是前置攝像頭,后置攝像頭,麥克風(音頻輸入)

@property(nonatomic, strong) AVCaptureDevice *device;

//AVCaptureDeviceInput 代表輸入設備,他使用AVCaptureDevice 來初始化

@property(nonatomic, strong) AVCaptureDeviceInput *input;

//輸出圖片

@property(nonatomic ,strong) AVCaptureStillImageOutput *imageOutput;

//session:由他把輸入輸出結合在一起,并開始啟動捕獲設備(攝像頭)

@property(nonatomic, strong) AVCaptureSession *session;

//圖像預覽層,實時顯示捕獲的圖像

@property(nonatomic ,strong) AVCaptureVideoPreviewLayer *previewLayer;

- (void)cameraDistrict{

self.device = [self cameraWithPosition:AVCaptureDevicePositionBack];//后置攝像頭

self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:nil];

self.imageOutput = [[AVCaptureStillImageOutput alloc] init];

self.session = [[AVCaptureSession alloc] init];

//? ? 拿到的圖像的大小可以自行設定

self.session.sessionPreset = AVCaptureSessionPreset640x480;

//輸入輸出設備結合

if ([self.session canAddInput:self.input]) {

[self.session addInput:self.input];

}

if ([self.session canAddOutput:self.imageOutput]) {

[self.session addOutput:self.imageOutput];

}

//預覽層的生成?

self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];

self.previewLayer.frame = CGRectMake(0, 0, screenWidth, screenHeight-94);

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)photoBtnDidClick

{

AVCaptureConnection *conntion = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];

if (!conntion) {

NSLog(@"拍照失敗!");

return;

}

[self.imageOutput captureStillImageAsynchronouslyFromConnection:conntion completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {

if (imageDataSampleBuffer == nil) {

return ;

}

NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];

//self.image = [UIImage imageWithData:imageData];

//停止抓取

[self.session stopRunning];

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容