Adjust text size to fit SKLabelNode with fixed width

2.2k views Asked by At

New to Spritekit and trying to fix the width of a SKLabelNode and then adjust the font of text to fit within the node accordingly.

Have been looking through the docs but cant seem to find anything suitable, like the UILabel function:

A UILabel.adjustsFontSizeToFitWidth = true

Thanks

1

There are 1 answers

2
Aidan Kaiser On

This is a nice function that I found a while back, but I can't remember exactly where

    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)
}

This adjusts the font size of the label to fit the width exactly, but you may want to change the function in order to add some extra padding on all sides.