我正在尝试在我的 iPhone 应用程序中嵌入一个简单的 View 来快速拍摄快照。一切正常,但我在相机启动时遇到了一些问题。在 Apple 示例项目中,AVCaptureSession 的 -startRunning
没有在主线程上执行,这似乎是必要的。我在 View 初始化期间设置捕获 session ,并在单独的线程中启动它。现在我在 -didMoveToSuperview
中添加了 AVCaptureVideoPreviewLayer
。没有多线程一切都很好(UI 被阻塞大约一秒钟)但是使用 GCD UI 有时可以工作,有时 UI 需要很长时间才能“解冻”或显示预览。
如何以可靠的方式处理相机的启动延迟,而不阻塞主线程(延迟本身不是问题)?
我希望你们能理解我的问题:D
提前致谢!
顺便说一句:这是我的概念验证项目(没有 GCD),我现在正在为另一个应用程序重用:http://github.com/dariolass/QuickShotView
最佳答案
所以我自己想通了。这段代码对我有用并且产生最少的 UI 卡住:
- (void)willMoveToSuperview:(UIView *)newSuperview {
//capture session setup
AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:self.rearCamera error:nil];
AVCaptureStillImageOutput *newStillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:
AVVideoCodecJPEG, AVVideoCodecKey,
nil];
[newStillImageOutput setOutputSettings:outputSettings];
AVCaptureSession *newCaptureSession = [[AVCaptureSession alloc] init];
if ([newCaptureSession canAddInput:newVideoInput]) {
[newCaptureSession addInput:newVideoInput];
}
if ([newCaptureSession canAddOutput:newStillImageOutput]) {
[newCaptureSession addOutput:newStillImageOutput];
self.stillImageOutput = newStillImageOutput;
self.captureSession = newCaptureSession;
}
// -startRunning will only return when the session started (-> the camera is then ready)
dispatch_queue_t layerQ = dispatch_queue_create("layerQ", NULL);
dispatch_async(layerQ, ^{
[self.captureSession startRunning];
AVCaptureVideoPreviewLayer *prevLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.captureSession];
prevLayer.frame = self.previewLayerFrame;
prevLayer.masksToBounds = YES;
prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
prevLayer.cornerRadius = PREVIEW_LAYER_EDGE_RADIUS;
//to make sure were not modifying the UI on a thread other than the main thread, use dispatch_async w/ dispatch_get_main_queue
dispatch_async(dispatch_get_main_queue(), ^{
[self.layer insertSublayer:prevLayer atIndex:0];
});
});
}
关于iphone - 通过 AVFoundation 使用 iPhone 相机时如何避免阻塞 UI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15841058/