2012-10-16 80 views
9

我有一個模擬拍照的AV基金會應用程序(如相機應用程序)。通常情況下,以下對我有用,但不在此例中。模擬「拍照」屏幕閃光燈

該代碼在我的視圖控制器中的一個動作中執行。它包含一個全屏UIView(videoPreviewLayer),它附帶了一個AVCaptureVideoPreviewLayer。動畫執行但沒有顯示。另請注意,我正在使用ARC,iOS 6,iPhone 4S,iPad3。

// Flash the screen white and fade it out 
UIView *flashView = [[UIView alloc] initWithFrame:[[self videoPreviewView] frame]]; 
[flashView setBackgroundColor:[UIColor whiteColor]]; 
[[[self view] window] addSubview:flashView]; 

[UIView animateWithDuration:1.f 
      animations:^{ 
       [flashView setAlpha:0.f]; 
      } 
      completion:^(BOOL finished){ 
       [flashView removeFromSuperview]; 
      } 
]; 

這裏是我附上AVCaptureVideoPreviewLayer:

// Setup our preview layer so that we can display video from the camera 
captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession]; 

CALayer *viewLayer = videoPreviewView.layer; 
viewLayer.masksToBounds = YES; 

captureVideoPreviewLayer.frame = videoPreviewView.bounds; 

[viewLayer insertSublayer:captureVideoPreviewLayer below:[[viewLayer sublayers] objectAtIndex:0]]; 

注意經過進一步調查,閃光燈雖然發生間歇性。一般來說,它應該在啓動後大約5-10秒後才能看到。即使我曾經調用過代碼,我也看到它會快速連續運行兩次。

回答

4

我的問題是從AV基金會回調中調用「flash」代碼。回調沒有在主線程上運行,因此任何UI代碼都無法正確執行。該解決方案是做這樣的事情:

dispatch_async(dispatch_get_main_queue(), ^{ /* execute flash code */ }); 
4

代碼爲swift3

let shutterView = UIView(frame: cameraView.frame) 
shutterView.backgroundColor = UIColor.black 
view.addSubview(shutterView) 
UIView.animate(withDuration: 0.3, animations: { 
    shutterView.alpha = 0 
}, completion: { (_) in 
    shutterView.removeFromSuperview() 
})