我正试图在场景的中心得到一些特定大小的文本。
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),因为锚点是0.5,0.5。然而,我明白这一点:

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)
}发布于 2017-06-13 04:25:57
看看horizontalAlignmentMode和verticalAlignmentMode of a SKLabelNode。它有点像标签的“锚点”,可以用来调整SKLabelNode中文本的水平和垂直位置。
默认情况下,verticalAlignmentMode设置为.baseline,horizontalAlignmentMode设置为.center。因此,“原产地”并不完全是在标签的(中心,中心)。
不知道这是否是您要寻找的效果,但如果您希望标签在场景中居中,我只需在addCubeExperienceLabel方法中添加以下行:
price.position = CGPoint.zero
price.verticalAlignmentMode = .center 
price.horizontalAlignmentMode = .center  如果希望文本从屏幕中心开始,请将horizontalAlignmentMode设置为.left。现在,文本的中心在屏幕的中心。
注意,标签的位置在addCubeExperienceLabel中设置,而不是在adjustLabelFontSizeToFitRect中设置。如果您调整标签的字体大小,它应该仍然保持在它的位置,就像一个普通的SKSpriteNode在调整它的大小后保持在它的位置一样。
希望这能有所帮助!
https://stackoverflow.com/questions/44510596
复制相似问题