Using TextNode sizes to produce a frame,I cant figure it out

Ive been trying to create a background behind some text, but when I use the TextNode values then background does not fit correctly. Here is a quick example that shows what I am doing and will display the problem I have.

# Create nodepath and nodes
myPath = NodePath('myPath')
myPGItem = PGItem('myPGItem')
myTextNode = TextNode('myText')

# Set the text of the textNode
myTextNode.setText('(text)')

# Setup a frame style and apply to the PGItem
myFrameStyle = PGFrameStyle()
myFrameStyle.setType(PGFrameStyle.TFlat)
myFrameStyle.setColor(0.5, 0.5, 0.5, 1)
myPGItem.setFrameStyle(0, myFrameStyle)

# Get the frame size of the textNode and apply
# to the PGItem
myTextNodeFrameSize = myTextNode.getCardActual()
myPGItem.setFrame(myTextNodeFrameSize)

# Attach the PGItem and the textNode to the nodepath
myPath.attachNewNode(myPGItem)
myPath.attachNewNode(myTextNode)

# Set the nodePath position
myPath.setPos(-1, 0, -0.5)

# Parent the path to aspect2d
myPath.reparentTo(aspect2d)

run()

Any advice greatly appreciated.

The card size computed by the TextNode relies on the extents as reported by the font. This allows room for the tallest capital letter, plus the space between lines, so it often leaves quite a bit of extra space on the top. Some fonts are better at this than others.

If you really want a card that fits tightly around the text, you can use NodePath.getTightBounds(), which examines the actual vertices contained within the NodePath and reports the minimum and maximum of the bounding box around all of the vertices. The only downside of this approach is that, if you have two different text strings side by side, they may have different heights depending on the letters used in the text strings, so they may not match visually.

Here’s your example modified to use the getTightBounds() call.

# Create nodepath and nodes
myPath = NodePath('myPath')
myPGItem = PGItem('myPGItem')
myTextNode = TextNode('myText')

# Set the text of the textNode
myTextNode.setText('(text)')

# Setup a frame style and apply to the PGItem
myFrameStyle = PGFrameStyle()
myFrameStyle.setType(PGFrameStyle.TFlat)
myFrameStyle.setColor(0.5, 0.5, 0.5, 1)
myPGItem.setFrameStyle(0, myFrameStyle)

# Get a tight bounds around the text and apply
# to the PGItem
np, xp = NodePath(myTextNode).getTightBounds()
myPGItem.setFrame(np[0], xp[0], np[2], xp[2])

# Attach the PGItem and the textNode to the nodepath
myPath.attachNewNode(myPGItem)
myPath.attachNewNode(myTextNode)

# Set the nodePath position
myPath.setPos(-1, 0, -0.5)

# Parent the path to aspect2d
myPath.reparentTo(aspect2d)

David

Thanks David. I did think it was something to do with the actual height of the font. Im sure the tight bounds will be what Im after.

Thanks for the info.