首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何设置SKLabelNode的字体大小以适应固定大小(Swift)

如何设置SKLabelNode的字体大小以适应固定大小(Swift)
EN

Stack Overflow用户
提问于 2015-06-22 21:14:10
回答 2查看 7.5K关注 0票数 21

我有一个带有SKLabelNode的正方形(200X200)。标签上写着分数,它可能会达到一个大的数字。我想把这个数字放在平方中。

如何更改SKLabelNode的文本大小(或大小)以使其适合固定大小。

EN

回答 2

Stack Overflow用户

发布于 2015-08-31 01:46:43

我写了这个宽度,但您可以调整它的高度,以适应您的CGRect。在本例中,pg是使用您使用的字体初始化的SKLabelNode。参数是字符串和目标宽度,结果是要分配给SKLabelNode的大小。当然,你也可以直接放入你的SKLabelNode。如果尺寸太大,则最大尺寸为50,但这是个人隐私。

代码语言:javascript
复制
 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))
}

编辑:实际上,我刚刚意识到我也写了这篇文章:

代码语言:javascript
复制
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
    }
票数 2
EN

Stack Overflow用户

发布于 2019-07-09 23:53:32

这种对mike663答案的扩展对我来说很有效,而且比一次处理1个像素要快得多。

代码语言:javascript
复制
// 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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30980918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档