Search code examples
swiftswiftuivisionosvisionos-simulator

Show Image in ImmersiveSpace


I'm playing around with VisionOS and wondered if it's possible to display an Image in ImmersiveSpace. From the docs: https://developer.apple.com/documentation/SwiftUI/ImmersiveSpace

I see a way to create ImmersiveSpace but it's not clear how can I encapsulate an Image inside of it (and let users see it as an immersive experience).

Any help will be highly appreciated!


Solution

  • To render an image in an immersive space, load an image as a texture, create a material with that texture, and attach a model component with that material to an entity inside RealityView. The code will look something like this:

     var body: some View {
       ZStack {
          RealityView { content in
             
             // Load the texture
             guard let texture = try? Texture.load(named: "sampleImage", in: nil) else {
                fatalError("Failed to load texture.")
             }
             
             // Create unlit material
             var material = UnlitMaterial()
             
             // Set properties
             material.color = .white
             material.texture = texture
             
             
             let entity = Entity()
             entity.components.set(ModelComponent(mesh: .generatePlane(width: 1, height: 1), materials: [material]))
             
             
          }
       }
    }