【发布时间】:2012-02-24 09:37:09
【问题描述】:
我想知道是否可以在 iPhone 应用程序中接收有关自动对焦的通知?
IE,是否存在一种在自动对焦开始、结束、成功或失败时收到通知的方法...?
如果有,这个通知名称是什么?
【问题讨论】:
标签: iphone camera notifications observer-pattern autofocus
我想知道是否可以在 iPhone 应用程序中接收有关自动对焦的通知?
IE,是否存在一种在自动对焦开始、结束、成功或失败时收到通知的方法...?
如果有,这个通知名称是什么?
【问题讨论】:
标签: iphone camera notifications observer-pattern autofocus
您可以通过观察AVCaptureDeviceInput.device.isAdjustingFocus 属性,使用现代 Swift 键值观察 api 在聚焦开始和结束时获取回调。在下面的示例中,AVCaptureDeviceInput 的实例称为captureDeviceInput。
例子:
self.focusObservation = observe(\.captureDeviceInput.device.isAdjustingFocus, options: .new) { _, change in
guard let isAdjustingFocus = change.newValue else { return }
print("isAdjustingFocus = \(isAdjustingFocus)")
}
【讨论】:
斯威夫特 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)")
}
}
【讨论】:
我为我的案例找到了自动对焦开始/结束时间的解决方案。它只是处理 KVO(Key-Value Observing)。
在我的 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"];
(...)
}
文档:
【讨论】: