iPhone:相机自动对焦观察者?

17

我想知道是否有可能在iPhone应用程序中收到关于自动对焦的通知?

例如,是否存在一种方式可以在自动对焦开始、结束、成功或失败时得到通知?

如果有的话,这个通知的名称是什么?

4个回答

44

我找到了解决方案,以便在自动对焦开始/结束时找到。这很简单,只需使用KVO(键值观察)即可。

在我的UIViewController中:

// callback
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if( [keyPath isEqualToString:@"adjustingFocus"] ){
        BOOL adjustingFocus = [ [change objectForKey:NSKeyValueChangeNewKey] isEqualToNumber:[NSNumber numberWithInt:1] ];
        NSLog(@"Is adjusting focus? %@", adjustingFocus ? @"YES" : @"NO" );
        NSLog(@"Change dictionary: %@", change);
    }
}

// register observer
- (void)viewWillAppear:(BOOL)animated{
    AVCaptureDevice *camDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    int flags = NSKeyValueObservingOptionNew; 
    [camDevice addObserver:self forKeyPath:@"adjustingFocus" options:flags context:nil];

    (...)   
}

// unregister observer
- (void)viewWillDisappear:(BOOL)animated{
    AVCaptureDevice *camDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    [camDevice removeObserver:self forKeyPath:@"adjustingFocus"];

    (...)
}

文档:


这并不告诉你自动对焦是否失败。即使调整对焦变为false,也不一定意味着相机已经对焦。 - Kostub Deshmukh
1
该方法在iPhone 6/6Plus/6S/6S Plus等设备上也会失败,因为存在不同的自动对焦模式,其中调整对焦并不准确。 - Sean Langley
ISO的键的值是多少? - nr5
1
感谢Sean Langley提供这些有用的信息。根据Apple的文档:“注:在使用对比度检测自动对焦的旧设备上,AVCaptureDevice adjustingFocus 的值会在自动对焦过程中发生变化。对于具有聚焦像素的设备,对焦变化较小且更频繁,因此该属性的值在对焦期间不会发生变化。相反,观察 lensPosition 属性以查看镜头移动。 - Laurent Maquet

6

Swift 3

在你的AVCaptureDevice实例上设置聚焦模式:

do {
     try videoCaptureDevice.lockForConfiguration()
     videoCaptureDevice.focusMode = .continuousAutoFocus
     videoCaptureDevice.unlockForConfiguration()
} catch {}

添加观察者:

videoCaptureDevice.addObserver(self, forKeyPath: "adjustingFocus", options: [.new], context: nil)

重写 observeValue 方法:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

    guard let key = keyPath, let changes = change else { 
        return
    }

    if key == "adjustingFocus" {

        let newValue = changes[.newKey]
        print("adjustingFocus \(newValue)")
    }
}

3

您可以使用现代的Swift键值观察API,通过观察AVCaptureDeviceInput.device.isAdjustingFocus属性,在聚焦开始和结束时获取回调。在下面的示例中,AVCaptureDeviceInput的实例被称为captureDeviceInput

示例:

self.focusObservation = observe(\.captureDeviceInput.device.isAdjustingFocus, options: .new) { _, change in
    guard let isAdjustingFocus = change.newValue else { return }

    print("isAdjustingFocus = \(isAdjustingFocus)")

}

0

在Swift中,您可以像这样做:

self.observation = videoDeviceInput.device.observe(\.isAdjustingFocus, options: [.old, .new]) { (object, change) in
     print("isAdjustingFocus, old = \(change.oldValue), new = \(change.newValue)")
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接