ARKit应用之导航

概述

ARKit 2.0发布以来,iOS端AR类应用层出不穷。由于其强大的功能,许多人们对于AR应用的美好设想都一一实现。
AR(Augmented Reality)的最初定义,就是增强现实(或扩增现实),即在外部设备的辅助下增强现实生活的感官体验。AR的本质也是虚拟,是在现实世界之上叠加虚拟场景以提供更加直观或有趣的信息。
基于这一定义,人们很容易想到利用AR看到周边街景中被遮挡的部分,并显示其基本信息的应用场景。利用手机这一外部辅助设备,内置摄像头捕捉到的画面就是现实景观,开发者可以在摄像头的实景之上添加想要添加的3D标注,并附以有用的信息,简单的AR导航就得能以实现。

基础

该功能的实现核心是基于CoreLocation的实时定位功能与ARKit的图层的结合。实现的基础除ARKit和iOS 11.0+以外,还借鉴了GitHub开源项目ARKit+CoreLocation提供的ARCL工具类,建议首先仔细阅读此项目中源码,领悟实现思想和逻辑。

实现

前期准备工作

项目中代码使用Swift 4.2 编写。
1.首先,在项目中引入上文中提到的 ARCL中的Source部分,或者直接pod ‘ARCL’。
其中各文件中代码的作用可以从他们的命名中一目了然,这里就不做赘述,参见以下文件目录结构:

Source
├── CGPoint+Extensions.swift
├── CLLocation+Extensions.swift
├── FloatingPoint+Radians.swift
├── LocationManager.swift
├── LocationNode.swift
├── SCNNode+Extensions.swift
├── SCNVector3+Extensions.swift
├── SceneLocationEstimate+Extensions.swift
├── SceneLocationEstimate.swift
└── SceneLocationView.swift

2.在Plist中加入NSCameraUsageDescription和NSLocationWhenInUseUsageDescription的key并添加简短描述。

  1. 改写ARCL中的LocationNode.swift,即构造你需要的标注样式和内容。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    open class LocationAnnotationNode: LocationNode {
    ///An image to use for the annotation
    ///When viewed from a distance, the annotation will be seen at the size provided
    ///e.g. if the size is 100x100px, the annotation will take up approx 100x100 points on screen.
    public let image: UIImage

    ///Subnodes and adjustments should be applied to this subnode
    ///Required to allow scaling at the same time as having a 2D 'billboard' appearance
    public let annotationNode: SCNNode

    ///Whether the node should be scaled relative to its distance from the camera
    ///Default value (false) scales it to visually appear at the same size no matter the distance
    ///Setting to true causes annotation nodes to scale like a regular node
    ///Scaling relative to distance may be useful with local navigation-based uses
    ///For landmarks in the distance, the default is correct
    public var scaleRelativeToDistance = false


    public init(location: CLLocation?, image: UIImage, title: String, distance: String) {
    self.image = image

    let frame: CGRect = CGRect(x:0.0, y:0.0, width:200.0, height:82.0)
    let bgImageView = UIImageView.init(frame: frame)
    bgImageView.image = image

    let titleLabel = UILabel.init(frame: CGRect(x: 0.0, y: 0.0, width: 120.0, height: 60.0))
    titleLabel.textColor = UIColor.darkText
    titleLabel.font = UIFont.boldSystemFont(ofSize: 18.0)
    titleLabel.text = title
    titleLabel.textAlignment = NSTextAlignment.center
    bgImageView.addSubview(titleLabel)

    let distanceLabel = UILabel.init(frame: CGRect(x: 120.0, y: 0.0, width: 80.0, height: 60.0))
    distanceLabel.textColor = UIColor.init(red: 19.0/255.0, green: 115.0/255.0, blue: 114.0/255.0, alpha: 1.0)
    distanceLabel.font = UIFont.systemFont(ofSize: 16.0)
    distanceLabel.text = distance
    distanceLabel.textAlignment = NSTextAlignment.center
    bgImageView.addSubview(distanceLabel)


    let plane = SCNPlane(width: frame.size.width/100, height: frame.size.height/100)
    plane.firstMaterial!.diffuse.contents = bgImageView
    plane.firstMaterial!.lightingModel = .constant

    annotationNode = SCNNode()
    annotationNode.geometry = plane

    super.init(location: location)

    self.name = title
    self.distance = distance
    self.distanceLabel = distanceLabel

    let billboardConstraint = SCNBillboardConstraint()
    billboardConstraint.freeAxes = SCNBillboardAxis.Y
    constraints = [billboardConstraint]

    addChildNode(annotationNode)
    }

以上代码的作用是使用位置名称和距离创建标注,返回一个带标题和距离信息的气泡,注意:这里的距离是实时变化的,也就是在初始化时给定一个初始值,而在获取到的位置信息后通过计算实时进行更新,以达到动态更新场景的效果

呈现

在以上准备工作的基础上,我们需要将AR标注实时呈现在摄像头中。
因此我们需要初始化SceneLocationViewMKMapView,并完成相关配置。

  • 初始化sceneLocationView

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    sceneLocationView.locationDelegate = self as? SceneLocationViewDelegate
    // Set to true to display am arrow wjoch points north.
    sceneLocationView.orientToTrueNorth = false
    sceneLocationView.showAxesNode = true
    if displayDebugging {
    sceneLocationView.showFeaturePoints = true
    }
    buildData().forEach {
    sceneLocationView.addLocationNodeWithConfirmedLocation(locationNode: $0)
    }
    view.addSubview(sceneLocationView)
  • 初始化mapView

    1
    2
    3
    4
    5
    6
    if !showMapView {
    mapView.delegate = self as? MKMapViewDelegate
    mapView.showsUserLocation = true
    mapView.isHidden = true
    view.addSubview(mapView)
    }

使用LocationAnnotationNodeinit方法创建标注点。

1
2
3
4
5
6
func buildNode(latitude: CLLocationDegrees, longtitude: CLLocationDegrees, altitude: CLLocationDistance, imageName: String, title: String, distance: String) -> LocationAnnotationNode {
let location = CLLocation(coordinate: CLLocationCoordinate2D(latitude: latitude, longitude: longtitude), altitude: altitude)
let image = UIImage(named: imageName)!

return LocationAnnotationNode(location: location, image: image, title: title, distance: distance)
}

再利用定时器连续且间断地更新标注信息。

1
2
3
4
5
6
// Update user location and show distance from current location to nodes added
updateUserLocationTimer = Timer.scheduledTimer(timeInterval: 3.0,
target: self,
selector: #selector(ViewController.updateUserLocation),
userInfo: nil,
repeats: true)

在适当的时候更新距离信息即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@objc func updateUserLocation() {
guard let currentLocation = sceneLocationView.currentLocation() else {
return
}

DispatchQueue.main.async {
if let bestEstimate = self.sceneLocationView.bestLocationEstimate(), let position = self.sceneLocationView.currentScenePosition() {
print("------------------------------------")
print("Fetch current location")
print("Best location estimate, position: \(bestEstimate.position), location: \(bestEstimate.location.coordinate), accurace: \(bestEstimate.location.horizontalAccuracy)")
print("current position: \(position)")

let translation = bestEstimate.translatedLocation(to: position)
print("translation: \(translation)")
print("translated location: \(currentLocation)")
print("------------------------------------")

// Location nodes
for node in self.sceneLocationView.locationNodes {
let distance = currentLocation.distance(from: node.location)
var distanceStr: String = String(format: "%.0fm", distance)
if distance >= 1000 {
distanceStr = String(format: "%.1fkm", (distance/1000))
}
node.distance = distanceStr
node.distanceLabel.text = distanceStr
}
}
}
}

以上。