Adjust text size to fit fixed width SKLabelNode

New to Spritekit and try to fix the width of SKLabelNode , and then edit the font of the text so that it matches the node.

We looked through docs , but could not find anything suitable, for example, UILabel :

A UILabel.adjustsFontSizeToFitWidth = true

thanks

+8
swift2 sprite-kit sklabelnode
source share
1 answer

This is a nice feature that I found a while ago, 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 allows you to adjust the font size on the label to exactly match the width, but you can change the function to add an extra padding on all sides.

+3
source share

All Articles