mabarif
mabarif

Reputation: 345

How to use RealityKit's image AnchorEntity in SwiftUI?

I want to use RealityKit's AnchorEntity initialized with an Anchoring Component Target of type Image. Here is what I am trying to do:

let anchorEntity = AnchorEntity(.image(group: "AR Resources", 
                                        name: "imgAnchor"))

I have found zero documentation on how to use this.

Does anyone know the right way to do it?

Upvotes: 4

Views: 1804

Answers (1)

Andy Jazz
Andy Jazz

Reputation: 58043

You can use AnchorEntity(.image(...)) in SwiftUI almost the same way as you used it in UIKit. At first click Assets.xcassets in Project Navigator pane and create AR Resources folder. Drag your image there. Setup its physical size in Inspector. Then copy/paste the code:

import SwiftUI
import RealityKit

struct ARViewContainer: UIViewRepresentable {
    
    func makeUIView(context: Context) -> ARView {
        
        let arView = ARView(frame: .zero)
        let entity = ModelEntity(mesh: .generateBox(size: 0.1))
        let anchor = AnchorEntity(.image(group: "AR Resources", 
                                          name: "image.png"))
        entity.setParent(anchor)
        arView.scene.anchors.append(anchor)
        return arView
    }
    func updateUIView(_ uiView: ARView, context: Context) { }
}

struct ContentView: View {
    var body: some View {
        ARViewContainer().edgesIgnoringSafeArea(.all)
    }
}

Upvotes: 5

Related Questions