如何从文档目录加载ARReferenceImage?

时间:2018-08-24 06:22:42

标签: ios swift swift4 arkit ios12

当前,我正在使用以下代码从Assets.xcassets的“ AR资源”中加载ARReferenceImage,

guard let trackingImages =  ARReferenceImage.referenceImages(inGroupNamed: "AR Resources", bundle: nil) else {
    print("Missing expected asset catalog resources.")
    return
}
configuration.trackingImages = trackingImages

现在,我正在将图像从服务器下载到iOS应用程序文档目录中名为“ Images”的自定义文件夹中。

如何将这些图像用作“跟踪图像”?

1 个答案:

答案 0 :(得分:4)

要从默认ARReference以外的指定位置加载自定义ARAssets Folder图像,您需要使用以下方法创建它们:

init(CGImage, orientation: CGImagePropertyOrientation, physicalWidth: CGFloat)

在此示例中,我使用ARWorldTrackingConfiguration,但是使用ARImageTrackingConfiguration的原理是相同的。

让我们说您将所有下载的图像存储到[UIImage]数组中,例如:

let imagesFromServer: [UIImage] = [UIImage(named: "gitHubIcon")!, UIImage(named: "stackOverflowIcon")!]

然后您可以使用类似以下的代码将它们变成ARReferenceImages

/// Converts An Array Of [UIImage] Into A Set Of ARReferenceImages
///
/// - Parameter images: [UIImage])
/// - Returns: Set<ARReferenceImage>
func loadedImagesFromDirectoryContents(_ images: [UIImage]) -> Set<ARReferenceImage>{

    var index = 0
    var customReferenceSet = Set<ARReferenceImage>()

    images.forEach { (downloadedImage) in

        //1. Convert The UIImage To A CGImage
        guard let cgImage = downloadedImage.cgImage else { return }

        //2. Get The Width Of The Image
        let imageWidth = CGFloat(cgImage.width)

        //3. Create A Custom AR Reference Image With A Unique Name
        let customARReferenceImage = ARReferenceImage(cgImage, orientation: CGImagePropertyOrientation.up, physicalWidth: imageWidth)
        customARReferenceImage.name = "MyCustomARImage\(index)"

        //4. Insert The Reference Image Into Our Set
        customReferenceSet.insert(customARReferenceImage)

        print("ARReference Image == \(customARReferenceImage)")

        index += 1


    }


    //5. Return The Set
    return customReferenceSet

}

请记住,ARWorldTrackingConfiguration需要一个Set<ARReferenceImage>

然后您可以像这样初始化您的自定义configurations detectionImages

 let detectionImages = loadedImagesFromDirectoryContents(imagesFromServer)

 configuration.detectionImages = detectionImages

 augmentedRealitySession.run(configuration, options: [.resetTracking, .removeExistingAnchors])

希望它会为您指明正确的方向...