2013-10-12 34 views
5

所以,我試圖使用AVFoundation實現相機。我想我做的都對。這是我在做什麼AVFoundation相機預覽圖層不起作用

  1. 通過設備創建會話
  2. 視頻類型獲取設備
  3. 環使相機在後面
  4. 使用#3所提到的設備獲取設備輸入和它添加到會話
  5. 創建類型的輸出AVCaptureStillImageOutput
  6. 設定的輸出設置,並把它添加到會話
  7. 得到的CALayer來回中號我認爲2
  8. 創建的AVCaptureVideoPreviewLayer
  9. 一個實例將其添加到#提到的層7
  10. 開始運行會話

那麼(下面我說的視圖會解釋)我有兩個意見一個在另一個上。最上面的是視圖1,下面的是視圖2.視圖1應該提供自定義攝像頭控件。

下面是代碼:

self.session = [[AVCaptureSession alloc]init]; 
[self.session setSessionPreset:AVCaptureSessionPresetHigh]; 
NSArray *devices = [[NSArray alloc]init]; 
devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; 
for (AVCaptureDevice *device in devices){ 
    if([device position] == AVCaptureDevicePositionBack){ 
     self.device = device; 
     break; 
    } 
} 
NSError *error; 
self.input = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:&error]; 
if([self.session canAddInput:self.input]){ 
    [self.session addInput:self.input];  
} 


self.stillImageOutput = [[AVCaptureStillImageOutput alloc]init]; 
NSDictionary *outputSettings = @{AVVideoCodecKey : AVVideoCodecJPEG}; 
[self.stillImageOutput setOutputSettings:outputSettings]; 

[self.session addOutput:self.stillImageOutput]; 

CALayer *cameraLayer = self.cameraView.layer; 
self.cameraView.backgroundColor = [UIColor clearColor]; 

AVCaptureVideoPreviewLayer *preview = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session]; 
[cameraLayer addSublayer:preview]; 

[self.session startRunning]; 

我得到的是視圖1(它有一個PNG圖片爲背景的圖像具有孔,使得其下的視圖,視圖可以是可見的。 )和視圖2是可見的,但我沒有看到我應該。因爲我更改了視圖2的背景顏色以清除顏色,所以我看到全是黑色的。我應該看看相機看到了什麼。

回答

7

原來你必須設置frame,maskToBounds和gravity以使預覽圖層正常工作。這就是我的做法

CALayer *cameraLayer = self.cameraView.layer; 
self.cameraView.backgroundColor = [UIColor clearColor]; 
[cameraLayer setMasksToBounds:YES]; 
AVCaptureVideoPreviewLayer *preview = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session]; 
[preview setVideoGravity:AVLayerVideoGravityResizeAspectFill]; 
[preview setFrame:[cameraLayer bounds]]; 


[cameraLayer addSublayer:preview];