本文译自官方文档 ARSession。为了保证翻译准确性,自己两确认两次,另外将其 API 进行了深入的注释。不足之处,请纠正。
ARSession 是一个单例,它是用于管理设备相机和 AR 运动过程的相关计算。说白了,它是管理 ARCamera 和 ARFrame;
一、简介
ARSession 对象是协调 ARKit 展示 AR 内容的,我叫它是 ARKit 的大管家。AR-Session 可以从相机硬件中读取数据,控制相机以及分析图片和展示图片。AR-Session 结合运行数据和相机展示出 AR内容。
每个 AR 应用需要建立一个 ARSession 对象,如果使用 ARSCNView 或者 ARSKView 对象展示 AR 视图 ,这些对象中自带 ARSession对象。如果你自己建立 AR 内容,你需要实例化和管理 ARSession 对象。
运行 ARSession 需要一个会话配置:一个 ARSessionConfiguration
实例或者其子类 ARWorldTrackingSessionConfiguration
.以上两个配置类,决定 ARkit 跟踪设备位置和运动并影响 AR 的用户体验。
二、 API
1. 配置 ARSession 和让会话工作
-
- runWithConfiguration:options:
设置好配置,并开启 ARSession 。 -
ARSessionRunOptions
Options affecting how to transition an AR session's current state when you change its configuration.
如果你修改 ARSession 配置,此属性选择决定如何过渡 AR 会话的当前状态。作用就是会话断开重连时的行为。 -
configuration
配置会话的运动和现场跟踪行为。 -
- pause
暂停 ARSession 所有工作,意思上说不让大管家工作了。
2. 响应 ARSession 更新
-
delegate
代理,提供接收捕捉到的图片和跟踪信息或响应会话状态的改变。 -
delegateQueue
指定代理执行的线程(主线程不会有延迟,子线程会有延迟),不指定的话默认主线程 -
ARSessionDelegate
实现其代理方法,可以从 ARSession 中拿到捕捉图像和追踪状态。 -
ARSessionObserver
实现其方法,当 ARSession 状态改变时,可以响应状态的改变。
3. 显示和在 AR 视图进行交互
-
currentFrame
ARSession 捕捉到当前最新图片的 Frame -
- addAnchor:
增加锚点 -
- removeAnchor:
移除特定的锚点。
4. 实例化 ARSession
5. 展开其观察者和代理
观察者是观察 ARSession 状态的变化,代理是告诉相机的位置和锚点的状况。
//session KVO观察者
@protocol ARSessionObserver <NSObject>
@optional
//session失败
- (void)session:(ARSession *)session didFailWithError:(NSError *)error;
//相机改变追踪状态
- (void)session:(ARSession *)session cameraDidChangeTrackingState:(ARCamera *)camera;
//session意外断开(如果开启ARSession之后,APP退到后台就有可能导致会话断开,或者别人打电话也会中断)
- (void)sessionWasInterrupted:(ARSession *)session;
//session会话断开恢复(短时间退到后台再进入APP会自动恢复)
- (void)sessionInterruptionEnded:(ARSession *)session;
@end
#pragma mark - ARSessionDelegate
@protocol ARSessionDelegate <ARSessionObserver>
@optional
//更新相机位置
- (void)session:(ARSession *)session didUpdateFrame:(ARFrame *)frame;
//添加锚点
- (void)session:(ARSession *)session didAddAnchors:(NSArray<ARAnchor*>*)anchors;
//刷新锚点
- (void)session:(ARSession *)session didUpdateAnchors:(NSArray<ARAnchor*>*)anchors;
//移除锚点
- (void)session:(ARSession *)session didRemoveAnchors:(NSArray<ARAnchor*>*)anchors;
@end
网友评论