Pietro Messineo
Pietro Messineo

Reputation: 837

Get name of reference image swift ARKit 1.5

Is someone know how can I get the name of the reference image red by the camera in AR?

I think that the Anchor is reading the identifier and connect it to the reference image that's returning name and physical size.

I want to have one AR Resources folder where I can put different images and then, in base of what the camera is recognize I want to display one model instead of another one.

Thank you very much!

Upvotes: 0

Views: 678

Answers (1)

PongBongoSaurus
PongBongoSaurus

Reputation: 7385

An ARReferenceImage has the following properties which you can access:

var name: String?

A descriptive name for the image.

var physicalSize: CGSize

The real-world dimensions, in meters, of the image.

As such, in order to get the name of the reference image and other properties you can use the following delegate callback:

func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {

        //1. If Out Target Image Has Been Detected Than Get The Corresponding Anchor
        guard let currentImageAnchor = anchor as? ARImageAnchor else { return }

        //2. Get The Targets Name
        let name = currentImageAnchor.referenceImage.name!

        //3. Get The Targets Width & Height
        let width = currentImageAnchor.referenceImage.physicalSize.width
        let height = currentImageAnchor.referenceImage.physicalSize.height

        //4. Log The Reference Images Information
        print("""
            Image Name = \(name)
            Image Width = \(width)
            Image Height = \(height)
            """)
    }

Note that this code assumes that your images have a name which is set in the ARResources Asset Folder e.g:

enter image description here

You can then put logic within the callback or call another function which adds an SCNNode or SCNScene at the transform of the ARImageAnchor e.g:

//1. Create An SCNNode
let nodeHolder = SCNNode()

//2. Determine Which ImageTarget Has Been Detected
if name == "ImageOne"{

    let nodeGeometry = SCNBox(width: 0.02, height: 0.02, length: 0.02, chamferRadius: 0)
    nodeGeometry.firstMaterial?.diffuse.contents = UIColor.cyan
    nodeHolder.geometry = nodeGeometry

}else if name == "ImageTwo"{

     let nodeGeometry = SCNSphere(radius: 0.02)
     nodeGeometry.firstMaterial?.diffuse.contents = UIColor.cyan
     nodeHolder.geometry = nodeGeometry
}

//3. Add The SCNNode At The Position Of The Anchor
nodeHolder.position = SCNVector3(currentImageAnchor.transform.columns.3.x,
                                         currentImageAnchor.transform.columns.3.y,
                                         currentImageAnchor.transform.columns.3.z)

//4. Add It To The Scene
augmentedRealityView?.scene.rootNode.addChildNode(nodeHolder)

Upvotes: 3

Related Questions