Search code examples
iosswiftscnnodescntext

How to calculate the distance between a SCNText's Center and its Left and Right Corners


How can I calculate distance between SCNText center and its left edge corner and its right edge corner.

For eg using the code below, if the word was "texas" the middle of the letter "x" would be the pivot point because it's in the middle of the word. How would I get the distance between the left side of the letter "t" and the letter "x". How would I get the distance between the right side of the letter "s" and the letter "x"

let material = SCNMaterial()
material.diffuse.contents = UIColor.red

let geometry = SCNText(string: "texas", extrusionDepth: 0.1)
geometry.flatness = 0
geometry.font = UIFont.systemFont(ofSize: 6.3)
geometry.materials = [material]

let textNode = SCNNode()
textNode.geometry = geometry
textNode.geometry?.firstMaterial?.isDoubleSided = true

// set pivot point 
let min = textNode.boundingBox.min
let max = textNode.boundingBox.max
textNode.pivot = SCNMatrix4MakeTranslation(
    min.x + (max.x - min.x)/2,
    min.y + (max.y - min.y)/2,
    min.z + (max.z - min.z)/2
)

Solution

  • let totalWidth: Float = textNode.boundingBox.max.x - textNode.boundingBox.min.x
    
    let halfWidth: Float = totalWidth / 2
    
    print("total width:", totalWidth)
    
    print("half width:", halfWidth)