8

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

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

1 回答 1

7

感谢@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)
}

这是另一个问题的链接。

于 2015-08-24T14:47:30.897 回答