【问题标题】:How to draw 3D object with core graphics in Swift?如何在 Swift 中使用核心图形绘制 3D 对象?
【发布时间】:2016-07-28 23:56:18
【问题描述】:

如何在 Swift 中使用核心图形绘制 3D 对象(最好是矩形)?

是否有可能或者我必须使用不同的库?

UIKit 可以吗?

【问题讨论】:

    标签: swift core-graphics


    【解决方案1】:

    借用这个答案:https://stackoverflow.com/a/24127282/887210

    您问题的关键部分是:

    SCNBox(width: 1, height: 4, length: 9, chamferRadius: 0)
    

    这会用 SceneKit 和 UIKit 绘制一个矩形框。它被设置为在您项目中的自定义 UIViewController 中使用,但它可以很容易地适应其他用途。

    示例代码:

    override func loadView() {
      // create a scene view with an empty scene
      let sceneView = SCNView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
      let scene = SCNScene()
      sceneView.scene = scene
    
      // default lighting
      sceneView.autoenablesDefaultLighting = true
    
      // a camera
      let cameraNode = SCNNode()
      cameraNode.camera = SCNCamera()
      cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)
      scene.rootNode.addChildNode(cameraNode)
    
      // a geometry object
      let box = SCNBox(width: 1, height: 4, length: 9, chamferRadius: 0)
      let boxNode = SCNNode(geometry: box)
      scene.rootNode.addChildNode(boxNode)
    
      // configure the geometry object
      box.firstMaterial?.diffuse.contents  = UIColor.red
      box.firstMaterial?.specular.contents = UIColor.white
    
      // set a rotation axis (no angle) to be able to
      // use a nicer keypath below and avoid needing
      // to wrap it in an NSValue
      boxNode.rotation = SCNVector4(x: 1, y: 1, z: 0.0, w: 0.0)
    
      // animate the rotation of the torus
      let spin = CABasicAnimation(keyPath: "rotation.w") // only animate the angle
        spin.toValue = 2.0*Double.pi
      spin.duration = 10
      spin.repeatCount = HUGE // for infinity
      boxNode.addAnimation(spin, forKey: "spin around")
    
      view = sceneView // Set the view property to the sceneView created here.
    }
    

    【讨论】:

    • 那么我如何将它整合到一个不是游戏的项目中。我可以将场景视图添加到我的视图控制器
    • 我已经更新了示例,以便您可以看到如何将它嵌入到 UIViewController 子类中。您基本上覆盖了loadView() 方法并将view 属性设置为sceneView 变量。
    • 最后一个快速问题,如何将其移动到我的视图控制器中的较小视图或对按钮说
    • 视图的大小无关紧要,绘图应适当缩放。只需将其放在 UIViewController 的子类中,并将视图控制器的类设置为该子类而不是 UIViewController。
    • 这个答案与问题不符。
    【解决方案2】:

    这个问题类似于是否可以在一张介于 2D 之间的纸上绘制 3D 对象的问题。三维效果是通过绘制附加线作为投影来实现的。第三维度也可以通过运动来感知,所以Core Animation可能是Core Graphics的伴侣,但它需要大量的计算,结果相当复杂(使用Core Animation)。

    实际上,SceneKit 或 Metal 是使用 Swift 绘制 3D 模型的选项。

    【讨论】:

      猜你喜欢
      • 2012-03-23
      • 2011-05-22
      • 1970-01-01
      • 2016-02-27
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多