Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust text size to fit SKLabelNode with fixed width

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

like image 200
dancingbush Avatar asked Dec 24 '16 17:12

dancingbush


1 Answers

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.

like image 115
Aidan Kaiser Avatar answered Nov 19 '22 21:11

Aidan Kaiser