【发布时间】:2016-07-28 23:56:18
【问题描述】:
如何在 Swift 中使用核心图形绘制 3D 对象(最好是矩形)?
是否有可能或者我必须使用不同的库?
UIKit 可以吗?
【问题讨论】:
标签: swift core-graphics
如何在 Swift 中使用核心图形绘制 3D 对象(最好是矩形)?
是否有可能或者我必须使用不同的库?
UIKit 可以吗?
【问题讨论】:
标签: swift core-graphics
借用这个答案: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.
}
【讨论】:
loadView() 方法并将view 属性设置为sceneView 变量。
这个问题类似于是否可以在一张介于 2D 之间的纸上绘制 3D 对象的问题。三维效果是通过绘制附加线作为投影来实现的。第三维度也可以通过运动来感知,所以Core Animation可能是Core Graphics的伴侣,但它需要大量的计算,结果相当复杂(使用Core Animation)。
实际上,SceneKit 或 Metal 是使用 Swift 绘制 3D 模型的选项。
【讨论】: