Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 547
mabarif Avatar asked Oct 23 '25 19:10

mabarif


1 Answers

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)
    }
}
like image 130
Andy Jazz Avatar answered Oct 26 '25 07:10

Andy Jazz