Scenekit - Scntext Centering Incorrectly

SceneKit - SCNText centering incorrectly

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);

Swift Scenekit - Centering SCNText - the getBoundingBoxMin:Max issue

OK so my final code solution looks like:

func setCounterValue(counterValue:Int) {

var v1 = SCNVector3(x: 0,y: 0,z: 0)
var v2 = SCNVector3(x: 0,y: 0,z: 0)

_textNode.removeFromParentNode()
_counterValue = counterValue

let newText = SCNText(string: String(format: "%08d", counterValue), extrusionDepth:sDepth)
newText.font = UIFont (name: "Arial", size: 3)
newText.firstMaterial!.diffuse.contents = UIColor.whiteColor()
newText.firstMaterial!.specular.contents = UIColor.whiteColor()

_textNode = SCNNode(geometry: newText)
_textNode.getBoundingBoxMin(&v1, max: &v2)

let dx:Float = Float(v1.x - v2.x)/2.0
let dy:Float = Float(v1.y - v2.y)
_textNode.position = SCNVector3Make(dx, dy, Float(sDepth/2))

node.addChildNode(_textNode)

}

I've left in my couple of global variables, but should make sense.

Thanks for the help all.

SCNText Alignment not working in iOS

It looks like alignment is working -- try adding a second line to your test string like "TEST\nT" and switching between left and right alignment modes. But SCNText adapts to fit the coordinate system of its node, so alignment alone won't necessarily make the text fit into your scene the way you want it to.

You can tweak how a node's content fits into its parent space using the node's pivot property. Set it to a translation transform (SCNMatrix4MakeTranslation) based on the bounding box of your text and you can change the layout however you like.

Rotate SCNText Node around center of itself (Swift - Scenekit)

you can set the node's pivot property to half its width and height (see getBoundingBoxMin:max:)

Center multi-line SCNtext on macOS SceneKit

It seems that it's the use of NSAttributedString that breaks the alignment. Removing the following line works as a workaround.

txt.string = NSAttributedString(string: "This\nis\ncentered", attributes: [.foregroundColor : NSColor.black])

Note that in any case SceneKit will use the SCNMaterial of the geometry to shade the object and won't take NSAttributedString.Key.foregroundColor into account.



Related Topics



Leave a reply



Submit