Resize a SKLabelNode font size to fit?

后端 未结 1 1162
我寻月下人不归
我寻月下人不归 2021-01-02 13:05

I\'m creating a label inside of sprite kit and setting an initial size. Since the app is to be localized, words may appear longer in other languages than their english versi

相关标签:
1条回答
  • 2021-01-02 13:29

    I was able to solve this thanks to a comment by @InvalidMemory and the answer by @mike663. Basically you scale the label in proportion to the rectangle that contains the label.

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

    Here is the link to the other question.

    0 讨论(0)
提交回复
热议问题