简体   繁体   中英

How to draw 3D object with core graphics in Swift?

How can I draw a 3D object (preferably a rectangle) with core graphics in Swift?

Is it possible or do I have to use a different library?

Is it possible with UIKit?

Borrowing from this answer: https://stackoverflow.com/a/24127282/887210

The key part for your question is:

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

This draws a rectangular box with SceneKit and UIKit. It's set up to be used in a custom UIViewController in your project but it can easily be adapted to other uses.

The example code:

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.redColor()
  box.firstMaterial?.specular.contents = UIColor.whiteColor()

  // 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*M_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.
}

This question is similar to the question whether it is possible to draw a 3D object on a sheet of paper which is, between, 2D. The third dimension effect is achieved drawing additional lines as the projections. The third dimension could also be perceived through the motion, so, Core Animation is a possible companion to Core Graphics but it requires a lot of calculation, as result, it is quite complicated (using Core Animation ).

Actually, SceneKit or Metal are the options to draw 3D models using Swift.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM