gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:13:13 25 4
gpt4 key购买 nike

我有一个正方形 (200X200),里面有一个 SKLabelNode。标签显示分数,它可以达到很大的数字。我想要适合广场上的数字。

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

最佳答案

可以将 SKLabelNode 的框架大小与给定的矩形进行比较。如果按标签矩形和所需矩形的大小比例缩放字体,则可以确定最佳字体大小以尽可能多地填充空间。最后一行方便地将标签移动到矩形的中心。 (如果文本只是小写字母或标点符号等短字符,它可能看起来会偏离中心。)

swift

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

目标-C

-(void)adjustLabelFontSizeToFitRect:(SKLabelNode*)labelNode rect:(CGRect)rect {

// Determine the font scaling factor that should let the label text fit in the given rectangle.
double scalingFactor = MIN(rect.size.width / labelNode.frame.size.width, rect.size.height / labelNode.frame.size.height);

// Change the fontSize.
labelNode.fontSize *= scalingFactor;

// Optionally move the SKLabelNode to the center of the rectangle.
labelNode.position = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect) - labelNode.frame.size.height / 2.0);
}

关于swift - 如何设置 SKLabelNode 的字体大小以适应固定大小(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30980918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com