且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Swift UI 中添加 3D 形状?

更新时间:2023-02-01 21:01:12

这里是演示如何使用球体设置 SceneKit 场景的最简单代码.希望有帮助.

Here is simplest code to demo how to setup SceneKit scene with your sphere. Hope it helps.

import SwiftUI
import SceneKit

struct SceneKitView: UIViewRepresentable {
    func makeUIView(context: UIViewRepresentableContext<SceneKitView>) -> SCNView {
        let sceneView = SCNView()
        sceneView.scene = SCNScene()
        sceneView.allowsCameraControl = true
        sceneView.autoenablesDefaultLighting = true
        sceneView.backgroundColor = UIColor.black

        let sphere = SCNSphere(radius: 2.0)
        sphere.firstMaterial?.diffuse.contents = UIColor.blue
        let spherenode = SCNNode(geometry: sphere)
        spherenode.position = SCNVector3(x: 0.0, y: 3.0, z: 0.0)

        sceneView.scene?.rootNode.addChildNode(spherenode)
        return sceneView
    }

    func updateUIView(_ uiView: SCNView, context: UIViewRepresentableContext<SceneKitView>) {

    }

    typealias UIViewType = SCNView
}

struct DemoSceneKit: View {
    var body: some View {
        SceneKitView()
    }
}

struct DemoSceneKit_Previews: PreviewProvider {
    static var previews: some View {
        DemoSceneKit()
    }
}