LoginSignup
9
9

More than 5 years have passed since last update.

SCNTextのPivotPointを中心に持って来る

Posted at

困ったこと

SCNTextをSCNNodeとして表示したときに思った場所に表示されず、若干のズレが生じた。
その理由はSCNTextを表示させた場合のSCNNodeのPivotPointは底面の中心では無く左下にあるかららしい。
この座標に文字を表示させたいという場合にはちょっと不便・・・。

IMG_0132.png
この様にデフォルトのまま配置すると原点の右上に文字が表示させる。

文字の中心にPivotPointを置きたい

デフォルトのPivotPointは(0,0,0)なのでこれを文字の中心に持って行く。
表示されるテキストの左下の座標はBoudingBoxのmin、右上はBoundingBoxのmaxで取得できる。
SCNNodeのメンバであるpivotはMatrixオブジェクトのためSCNMatrix4MakeTranslationでPivotPointを変更する。

IMG_0133.png

実際のコード

let text = SCNText(string: "Hello", extrusionDepth: 0)
text.font = UIFont(name: "San Francisco", size: 5 )
text.firstMaterial?.diffuse.contents = UIColor.green
let textNode = SCNNode(geometry: text)

let (min, max) = (textNode.boundingBox)
let w = Float(max.x - min.x)
let h = Float(max.y - min.y)
textNode.pivot = SCNMatrix4MakeTranslation(w/2 + min.x, h/2 + min.y, 0)

scene.rootNode.addChildNode(textNode)

変更後

変更後は思い通りの位置に表示される様になった。

IMG_0135.png
IMG_0134.png

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9