iphone - 通过 AVFoundation 使用 iPhone 相机时如何避免阻塞 UI?

标签 iphone ios camera avfoundation grand-central-dispatch

我正在尝试在我的 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/

相关文章:

android - 相机方向未在正确的 Android 模式下显示

ios - UITableView insertRows(位于: indexPath) returns error of invalid number of rows

ios - 使用 Storyboard 设置 UITextView 的最大行数,如 UILabel?

android - 如何通过html5访问手机上的特定摄像头

iphone - 应用程序不会在 Trigger.io 中保持纵向模式

iphone - 自动调整大小时如何在导航栏和 TabBar 中拉伸(stretch)背景图像

camera - 我可以将 Sony HDR-AS100 连接到现有接入点吗

iphone - 使用 iphone-exif 获取 EXIF 数据

iphone - 使用 Tapku Calendar 创建透明日历

ios - 在 UIAlertView 中添加颜色选择器