Search code examples
iosswiftsprite-kitsklabelnode

How to make text the same size on all devices in SpriteKit?


In SpriteKit, is there a way to make an SKLabelNode look the same size, regardless of the device, eg: Looks the same size on a iPhone 5 as a 6Plus?

I've tried using this method someone else recommended:

let textRect = CGRect(x: 0, y: 0, width: frame.width * 0.4, height: frame.height * 0.045)
let scalingFactor = min(textRect.width / text.frame.width, textRect.height / text.frame.height)
text.fontSize *= scalingFactor

But it doesn't make all text the same size, as words like "man" aren't as physically tall as words like "High" (due to it's "y" and "h" sticking out).

So is there a method to make text look the same size on all devices? At the moment I create the SKLabelNode like so:

let text = SKLabelNode(text: "Start")
text.fontSize = 30
text.position = CGPoint(x: 0, y: 0)
addChild(text)

Solution

  • The issue here is that you are trying to scale the fontSize, and this does not really play well with complex decimal numbers. Instead, after you create your label, just scale that to the scale factor that you are using to scale everything else

    let text = SKLabelNode(text: "Start")
    text.fontSize = 30
    text.position = CGPoint(x: 0, y: 0)
    
    text.xScale = xScaleFactor
    text.yScale = yScaleFactor
    

    where xScaleFactor and yScaleFactor are the factors you are using to determine your scale. (This number should only have to be calculated once, and then stored, if you are not doing that, I would recommend making that change)

    Basically in the code you provided it is done like this:

    let textRect = CGRect(x: 0, y: 0, width: frame.width * 0.4, height: frame.height * 0.045)
    let scaleFactorX = textRect.width / text.frame.width
    let scaleFactorY = textRect.height / text.frame.height