gpt4 book ai didi

ios - SpriteKit SKLabelNode 对齐

转载 作者:可可西里 更新时间:2023-11-01 02:04:08 24 4
gpt4 key购买 nike

我正在尝试以特定大小将一些文本居中放置在场景的中心。

func addCubeExperienceLabel(_ buttonSize : CGSize, _ buttonPos : CGPoint, _ world : Int) {
let price = SKLabelNode(fontNamed: "LCDSolid")
price.text = String(WorldPrices.fromInt(world).rawValue)
price.zPosition = 50
adjustLabelFontSizeToFitRect(labelNode: price, rect: CGRect(origin: CGPoint(x: 0, y: 0), size : buttonSize))
self.addChild(price)
}

所以我使用 adjustLabelFontSizeToFitRect:

adjustLabelFontSizeToFitRect(labelNode: price, rect: CGRect(origin: CGPoint(x: 0, y: 0), size : buttonSize))

调整SKNodeLabel的大小为特定大小。但我希望那个标签的原点是屏幕的中心,所以 (0,0),因为 anchor 是 0.5,0.5。但是,我明白了:

enter image description here

adjustLabelFontSizeToFitRect() 是这样的:

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

最佳答案

查看 SKLabelNode 的 horizo​​ntalAlignmentModeverticalAlignmentMode。它有点像标签的“ anchor ”,可用于调整 SKLabelNode 中文本的水平和垂直位置。

默认情况下,verticalAlignmentMode 设置为 .baseline,horizo​​ntalAlignmentMode 设置为 .center。所以“原点”并不完全在标签的(中心,中心)。

不知道这是否是您要寻找的效果,但如果您希望标签在场景中居中,我只需在 addCubeExperienceLabel 方法中添加这些行:

price.position = CGPoint.zero
price.verticalAlignmentMode = .center
price.horizontalAlignmentMode = .center

如果您希望文本在屏幕中心开始,请将 horizo​​ntalAlignmentMode 设置为 .left。现在文本的中心位于屏幕的中心。

请注意,标签的位置是在 addCubeExperienceLabel 中设置的,而不是在 adjustLabelFontSizeToFitRect 中设置的。如果你调整标签的字体大小,它应该仍然保持在它的位置,就像一个普通的 SKSpriteNode 在它的大小调整后保持在它的位置。

希望这对您有所帮助!

关于ios - SpriteKit SKLabelNode 对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44510596/

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