我有一个带有SKLabelNode
的正方形(200X200)。标签上写着分数,它可能会达到一个大的数字。我想把这个数字放在平方中。
如何更改SKLabelNode
的文本大小(或大小)以使其适合固定大小。
发布于 2015-08-31 01:46:43
我写了这个宽度,但您可以调整它的高度,以适应您的CGRect。在本例中,pg是使用您使用的字体初始化的SKLabelNode。参数是字符串和目标宽度,结果是要分配给SKLabelNode的大小。当然,你也可以直接放入你的SKLabelNode。如果尺寸太大,则最大尺寸为50,但这是个人隐私。
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))
}
编辑:实际上,我刚刚意识到我也写了这篇文章:
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
}
发布于 2019-07-09 23:53:32
这种对mike663答案的扩展对我来说很有效,而且比一次处理1个像素要快得多。
// 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
https://stackoverflow.com/questions/30980918
复制相似问题