使用AVCaptureSession显示相机预览
Posted 小敏的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用AVCaptureSession显示相机预览相关的知识,希望对你有一定的参考价值。
#import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> @interface ViewController : UIViewController @property (nonatomic,strong) AVCaptureSession * captureSession; @property (nonatomic,strong) AVCaptureDeviceInput * videoInput; @end
- (void)viewDidLoad { [super viewDidLoad]; self.captureSession = [[AVCaptureSession alloc] init]; self.captureSession.sessionPreset = AVCaptureSessionPresetHigh; AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; NSError * error = nil; self.videoInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error]; if (self.videoInput) { [self.captureSession addInput:self.videoInput]; }else{ NSLog(@"Input Error:%@",error); } AVCaptureVideoPreviewLayer * previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession]; UIView * aView = self.view; previewLayer.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-70); [aView.layer addSublayer:previewLayer]; }
- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.captureSession startRunning]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [self.captureSession stopRunning]; }
以上是关于使用AVCaptureSession显示相机预览的主要内容,如果未能解决你的问题,请参考以下文章
如何正确清理 AVCaptureSession 和 AVCaptureVideoPreviewLayer
iOS 相机 AVCaptureSession 在纵向与横向大小或分辨率