iOS使用AVCaptureSession自訂相機

來源:互聯網
上載者:User

iOS使用AVCaptureSession自訂相機

關於iOS調用攝像機來擷取照片,通常我們都會調用UIImagePickerController來調用系統提供的相機來拍照,這個控制項非常好用。但是有時UIImagePickerController控制項無法滿足我們的需求,例如我們需要更加複雜的OverlayerView,這時候我們就要自己構造一個攝像機控制項了。

這需要使用AVFoundation.framework這個framework裡面的組件了,所以我們先要匯入這個標頭檔,另外還需要的組件官方文檔是這麼說的:

● An instance of AVCaptureDevice to represent the input device, such as a camera or microphone
● An instance of a concrete subclass of AVCaptureInput to configure the ports from the input device
● An instance of a concrete subclass of AVCaptureOutput to manage the output to a movie file or still image
● An instance of AVCaptureSession to coordinate the data flow from the input to the output


這裡我只構造了一個具有拍照功能的照相機,至於錄影和錄音功能這裡就不加說明了。

總結下來,我們需要以下的對象:

@property (nonatomic, strong)       AVCaptureSession            * session;//AVCaptureSession對象來執行輸入裝置和輸出裝置之間的資料傳遞@property (nonatomic, strong)       AVCaptureDeviceInput        * videoInput;//AVCaptureDeviceInput對象是輸入資料流@property (nonatomic, strong)       AVCaptureStillImageOutput   * stillImageOutput;//照片輸出資料流對象,當然我的照相機只有拍照功能,所以只需要這個對象就夠了@property (nonatomic, strong)       AVCaptureVideoPreviewLayer  * previewLayer;//預覽圖層,來顯示照相機拍攝到的畫面@property (nonatomic, strong)       UIBarButtonItem             * toggleButton;//切換前後鏡頭的按鈕@property (nonatomic, strong)       UIButton                    * shutterButton;//拍照按鈕@property (nonatomic, strong)       UIView                      * cameraShowView;//放置預覽圖層的View 

我的習慣是在init方法執行的時候建立這些對象,然後在viewWillAppear方法裡載入預覽圖層。現在就讓我們看一下代碼就清楚了。

- (void) initialSession{    //這個方法的執行我放在init方法裡了    self.session = [[AVCaptureSession alloc] init];    self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self frontCamera] error:nil];    //[self fronCamera]方法會返回一個AVCaptureDevice對象,因為我初始化時是採用前網路攝影機,所以這麼寫,具體的實現方法後面會介紹    self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];    NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];    //這是輸出資料流的設定參數AVVideoCodecJPEG參數表示以JPEG的圖片格式輸出圖片    [self.stillImageOutput setOutputSettings:outputSettings];        if ([self.session canAddInput:self.videoInput]) {        [self.session addInput:self.videoInput];    }    if ([self.session canAddOutput:self.stillImageOutput]) {        [self.session addOutput:self.stillImageOutput];    }    }
這是擷取前後網路攝影機對象的方法

- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition) position {NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];for (AVCaptureDevice *device in devices) {if ([device position] == position) {return device;}}return nil;}- (AVCaptureDevice *)frontCamera {return [self cameraWithPosition:AVCaptureDevicePositionFront];}- (AVCaptureDevice *)backCamera {return [self cameraWithPosition:AVCaptureDevicePositionBack];}

接下來在viewWillAppear方法裡執行載入預覽圖層的方法

- (void) setUpCameraLayer{    if (_cameraAvaible == NO) return;        if (self.previewLayer == nil) {        self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];        UIView * view = self.cameraShowView;        CALayer * viewLayer = [view layer];        [viewLayer setMasksToBounds:YES];                CGRect bounds = [view bounds];        [self.previewLayer setFrame:bounds];        [self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];                [viewLayer insertSublayer:self.previewLayer below:[[viewLayer sublayers] objectAtIndex:0]];            }}

注意以下的方法,在viewDidAppear和viewDidDisappear方法中啟動和關閉session

- (void) viewDidAppear:(BOOL)animated{    [super viewDidAppear:animated];    if (self.session) {        [self.session startRunning];    }}- (void) viewDidDisappear:(BOOL)animated{    [super viewDidDisappear: animated];    if (self.session) {        [self.session stopRunning];    }}

接著我們就來實現切換前後鏡頭的按鈕,按鈕的建立我就不多說了

- (void)toggleCamera {    NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];if (cameraCount > 1) {        NSError *error;        AVCaptureDeviceInput *newVideoInput;        AVCaptureDevicePosition position = [[_videoInput device] position];                if (position == AVCaptureDevicePositionBack)            newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self frontCamera] error:&error];        else if (position == AVCaptureDevicePositionFront)            newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self backCamera] error:&error];        else            return;                if (newVideoInput != nil) {            [self.session beginConfiguration];            [self.session removeInput:self.videoInput];            if ([self.session canAddInput:newVideoInput]) {                [self.session addInput:newVideoInput];                [self setVideoInput:newVideoInput];            } else {                [self.session addInput:self.videoInput];            }            [self.session commitConfiguration];        } else if (error) {NSLog(@"toggle carema failed, error = %@", error);        }    }}

這是切換鏡頭的按鈕方法

- (void) shutterCamera{    AVCaptureConnection * videoConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];    if (!videoConnection) {        NSLog(@"take photo failed!");        return;    }        [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {        if (imageDataSampleBuffer == NULL) {            return;        }        NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];        UIImage * image = [UIImage imageWithData:imageData];        NSLog(@"image size = %@",NSStringFromCGSize(image.size));    }];}
這是拍照按鈕的方法

這樣自訂照相機的簡易功能就完成了,如果你想要再添加其他複雜的功能,可以參考一下下面這篇文章,希望對你們有所協助。

http://course.gdou.com/blog/Blog.pzs/archive/2011/12/14/10882.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.