2012-10-16 87 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() 
})