0

我需要在 3D 场景之上绘制 2D 图例、2D 框架等。在这里,我试图在 3D 球体顶部显示 2D 标签,以便标签始终面向用户,即使他们旋转场景。

我正在使用 SCNView 绘制 3D 场景(=> 工作正常) 我正在使用它的 NSView 父级(子类以覆盖其绘制功能)来显示 2D 文本(=> 不显示任何内容)

(var twoDCoordinates:CGPoint 是外部的)

在我的视图控制器中:

   @IBOutlet weak var sceneView: SCNView!
   func sceneSetup() {
      let scene = SCNScene()

      // (I set the light and the camera...)
      // Adding the sphere
      let geometry = SCNSphere (radius: 4.0)
      geometry.firstMaterial!.diffuse.contents = CGColor.red
      geometry.firstMaterial!.specular.contents = CGColor.white
      sphereNode = SCNNode (geometry: geometry)
      sphereNode.position = SCNVector3Make(-6, 0, 0)
      scene.rootNode.addChildNode (sphereNode)
      sceneView.scene = scene

      sceneView.allowsCameraControl = true
      // compute the 2D coordinates of the text to be displayed
      var q = sphereNode.position
      q.x += 6.0; q.y += 6.0; q.z += 6.0 // outside of the sphere
      let projected = sceneView.projectPoint (q)
      twoDCoordinates = CGPoint (x: projected.x, y: projected.y)
      sceneView.needsDisplay = true
  }

=> 3D球体正确显示;两个D坐标是正确的

在 TwoDView:NSView 类中(即场景视图容器)

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // Drawing code here.
      let paragraphStyle = NSMutableParagraphStyle()
      paragraphStyle.lineBreakMode = .byTruncatingTail
      paragraphStyle.alignment = .left
      let textAttributes = [
         NSAttributedString.Key.font: NSFont.systemFont(ofSize: 72.0),
         NSAttributedString.Key.paragraphStyle: paragraphStyle]
      let label = "Sphere Label"
      let size = label (withAttributes: textAttributes)
      let rect = CGRect(x: twoDCoordinates.x, y: twoDCoordinates.y, width: size.width, height: size.height)
      label.draw(in: rect, withAttributes: textAttributes)
   }

=> 函数 draw 被调用,但没有显示文本。

我希望文本“球体标签”显示在 3D 球体旁边,但只显示 3D 场景。即使调用了函数 draw。

4

0 回答 0