I'm creating a label inside of sprite kit and setting an initial size. Since the app is to be localized, words may appear longer in other languages than their english version. Therefore how can I adjust the font size of the label to fit within a certain width which in this case is the button.
myLabel = SKLabelNode(fontNamed: "Arial")
myLabel.text = "Drag this label"
myLabel.fontSize = 20
I was able to solve this thanks to a comment by @InvalidMemory and the answer by @mike663. Basically you scale the label in proportion to the rectangle that contains the label.
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)
}
Here is the link to the other question.