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

后端 未结 3 962
野性不改
野性不改 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

    I have written this for the width, but you can adapt it to the height to fit your CGRect. In the example, pg is a SKLabelNode initialized with the font you are using. Arguments are your String and the target width, and the result is the size you want to assign to your SKLabelNode. Of course, you can also put directly your SKLabelNode. If the size is too big, then the max size is 50, but that's personal.

     func getTextSizeFromWidth(s:String, w:CGFloat)->CGFloat {
    
        var result:CGFloat = 0;
        var fits:Bool = false
        pg!.text=s
        if(s != ""){
          while (!fits) {
            result++;
            pg!.fontSize=result
            fits = pg!.frame.size.width > w;
          }
        result -= 1.0
        }else{
            result=0;
        }
    
        return min(result, CGFloat(50))
    }
    

    Edit: Actually, I just realized I had also written this:

    extension SKLabelNode {
    func fitToWidth(maxWidth:CGFloat){
        while frame.size.width >= maxWidth {
            fontSize-=1.0
        }
    }
    
    func fitToHeight(maxHeight:CGFloat){
        while frame.size.height >= maxHeight {
            fontSize-=1.0
        }
    

提交回复
热议问题