How to set font size of SKLabelNode to fit in fixed size (Swift)

后端 未结 3 966
野性不改
野性不改 2020-12-29 06:21

I have a square (200X200) with a SKLabelNode in it. The label shows score and it my be reach a large number. I want fit the number in the square.

How c

3条回答
  •  佛祖请我去吃肉
    2020-12-29 06:34

    This expansion of mike663's answer worked for me, and gets there much quicker than going 1 pixel at a time.

    // Find the right size by trial & error...
    var testingSize: CGFloat = 0    // start from here
    var currentStep: CGFloat = 16   // go up by this much. It will be reduced each time we overshoot.
    var foundMatch = false
    
    while !foundMatch {
        var overShot = false
        while !overShot {
            testingSize += currentStep
            labelNode.fontSize = testingSize
            // How much bigger the text should be to perfectly fit in the given rectangle.
            let scalingFactor = min(rect.width / labelNode.frame.width, rect.height / labelNode.frame.height)
    
            if scalingFactor < 1         { overShot   = true }  // Never go over the space
            else if scalingFactor < 1.01 { foundMatch = true }  // Stop when over 99% of the space is filled
        }
        testingSize -= currentStep  // go back to the last one that didn't overshoot
        currentStep /= 4
    }
    labelNode.fontSize = testingSize // go back to the one we were happy with
    

提交回复
热议问题