SceneKit - SCNText centering incorrectly

前端 未结 4 1575
醉话见心
醉话见心 2020-12-31 23:13

I have tried to make a text string (SCNText) fit inside a box (SCNBox) in the code below. The size of the box looks correct but the text is not in the right center of the bo

相关标签:
4条回答
  • 2020-12-31 23:53

    To find the center of the bounding box you need to add (not subtract) the min and max before you divide by 2.

    textNode.position = SCNVector3(x: (minVec.x + maxVec.x) / 2, y: minVec.y + maxVec.y, z: 0)
    
    0 讨论(0)
  • 2020-12-31 23:57

    The difference of SCNText from other geometries is that SCNText origin point positioned at bottom left corner. In other geometries, it is a bottom center.

    To fix text position in parent node you can set its pivotPoint.x to half of width:

    SCNVector3 min, max;
    [textNode getBoundingBoxMin:&min max:&max];
    textNode.pivot = SCNMatrix4MakeTranslation((max.x - min.x) / 2, 0, 0);
    

    To fix subnodes position, you should set their position to half of width plus min:

    SCNVector3 min, max;
    [textNode getBoundingBoxMin:&min max:&max];
    subnode.position = SCNVector3Make((max.x - min.x) / 2 + min.x, (max.y - min.y) / 2 + min.y, 0);
    
    0 讨论(0)
  • 2020-12-31 23:57

    I think you might be getting bitten by SCNText's unusual treatment of origin. IIRC the Y zero is at the string's baseline, not at the bottom of the descenders.

    Turn on showBoundingBoxes In the debugOptions and see if that helps.

    0 讨论(0)
  • 2021-01-01 00:12

    Swift: center text-node in parent-node correctly

    let (min, max) = textNode.boundingBox
    
    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)
    
    let textNodeParent = SCNNode()
    textNodeParent.addChildNode(textNode)
    
    0 讨论(0)
提交回复
热议问题