程序效果:
程序代码:(您需要创建两个文件)
文件1(MyApp):
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
Reality()
}
}
}
文件2(Reality):
import SwiftUI
import RealityKit
struct Reality: View {
var body: some View {
ARViewContainer().edgesIgnoringSafeArea(.all)
}
}
struct ARViewContainer: UIViewRepresentable {
func makeUIView(context: Context) -> ARView {
let arView = ARView(frame: .zero, cameraMode: .ar, automaticallyConfigureSession: true)
let anchorEntity = AnchorEntity(plane: .horizontal)//水平类场景
let box = MeshResource.generateBox(size: 0.2/2, cornerRadius: 0.05/5)//形状
let material = SimpleMaterial(color: .blue, isMetallic: true)//颜色
let ARentity = ModelEntity(mesh: box, materials: [material])//实体(加载模型)
anchorEntity.addChild(ARentity)//锚点
arView.scene.anchors.append(anchorEntity)//场景
return arView
}
func updateUIView(_ uiView: ARView, context: Context) {
}
}
备注:本节生成了一个具有金属属性的正方体,然后展现它。