SpriteKit中CGRect的原点

时间:2017-06-13 00:26:18

标签: swift sprite-kit sklabelnode

我正在尝试将具有特定大小的文本放在场景中心。

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。但是,我明白了:

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

1 个答案:

答案 0 :(得分:1)

查看SKLabelNode的horizontalAlignmentModeverticalAlignmentMode。它有点像一个"锚点"用于标签,可用于调整SKLabelNode中文本的水平和垂直位置。

默认情况下,verticalAlignmentMode设置为.baseline,horizontalAlignmentMode设置为.center。所以"起源"并不完全在标签的(中心,中心)。

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

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

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

请注意,标签的位置设置在addCubeExperienceLabel而不是adjustLabelFontSizeToFitRect。如果您调整标签的字体大小,它仍应保持在其位置,就像正常的SKSpriteNode在调整其大小后保持在其位置一样。

希望这有帮助!