ARKit - How to contain SCNText within another SCNNode (speech bubble)

自作多情 提交于 2019-12-03 20:53:06

I had the same problem and finally I have solved it as following:

  • Create a SCNText and add it as a geometry to SCNNode:

    let string = "Coverin text with a plane :)"
    let text = SCNText(string: string, extrusionDepth: 0.1)
    text.font = UIFont.systemFont(ofSize: 1)
    text.flatness = 0.005
    let textNode = SCNNode(geometry: text)
    let fontScale: Float = 0.01
    textNode.scale = SCNVector3(fontScale, fontScale, fontScale)
    
  • Coordinate the text pivot form left bottom to center:

    let (min, max) = (text.boundingBox.min, text.boundingBox.max)
    let dx = min.x + 0.5 * (max.x - min.x)
    let dy = min.y + 0.5 * (max.y - min.y)
    let dz = min.z + 0.5 * (max.z - min.z)
    textNode.pivot = SCNMatrix4MakeTranslation(dx, dy, dz)
    
  • Create a PlaneNode and add the textNode as a childNode of the PlaneNode:

    let width = (max.x - min.x) * fontScale
    let height = (max.y - min.y) * fontScale
    let plane = SCNPlane(width: CGFloat(width), height: CGFloat(height))
    let planeNode = SCNNode(geometry: plane)
    planeNode.geometry?.firstMaterial?.diffuse.contents = UIColor.green.withAlphaComponent(0.5)
    planeNode.geometry?.firstMaterial?.isDoubleSided = true
    planeNode.position = textNode.position
    textNode.eulerAngles = planeNode.eulerAngles
    planeNode.addChildNode(textNode)
    
  • and at the end add the PlaneNode to sceneView:

    sceneView.scene.rootNode.addChildNode(planeNode)
    

and that's the result:

If you only need a white box behind your text I achieved it by doing this in my renderer function:

func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {

        let node = SCNNode()

        ............

        let testPlane = SCNPlane(width: someWidth, height: someHeight)


        let testScene = SKScene(size: CGSize(width: 900, height: 900))
        testScene.backgroundColor = UIColor.white

        let str = SKLabelNode(text: "This is just a test")
        str.color = UIColor.black
        str.fontColor = UIColor.black
        str.fontSize = 45.5

        str.position = CGPoint(x: stuff.size.width / 2,
                                 y: stuff.size.height / 2)
        testScene.addChild(str)

        testPlane.firstMaterial?.diffuse.contents = testScene
        testPlane.firstMaterial?.isDoubleSided = true
        testPlane.firstMaterial?.diffuse.contentsTransform = SCNMatrix4Translate(SCNMatrix4MakeScale(1, -1, 1), 0, 1, 0)

        let testNode = SCNNode(geometry: testPlane)


        testNode.eulerAngles.x = -.pi / 2
        testNode.position = SCNVector3Make(0.0,0.0,0.0)

        node.addChildNode(testNode)


}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!