调整SKLabelNode字体大小以适应?

时间:2015-08-21 15:57:07

标签: swift sprite-kit sklabelnode

我正在sprite kit中创建一个标签并设置初始大小。由于应用程序要进行本地化,因此其他语言中的单词可能比英语版本更长。因此,如何调整标签的字体大小以适应某个宽度,在这种情况下是按钮。

myLabel = SKLabelNode(fontNamed: "Arial")
myLabel.text = "Drag this label"
myLabel.fontSize = 20

1 个答案:

答案 0 :(得分:5)

由于@InvalidMemory的评论和@ mike663的回答,我能够解决这个问题。基本上,您可以根据包含标签的矩形按比例缩放标签。

func adjustLabelFontSizeToFitRect(labelNode:SKLabelNode, rect:CGRect) {

// Determine the font scaling factor that should let the label text fit in the given rectangle.
let scalingFactor = min(rect.width / labelNode.frame.width, rect.height / labelNode.frame.height)

// Change the fontSize.
labelNode.fontSize *= scalingFactor

// Optionally move the SKLabelNode to the center of the rectangle.
labelNode.position = CGPoint(x: rect.midX, y: rect.midY - labelNode.frame.height / 2.0)
}

以下是other question的链接。