【问题标题】:Origin point of a CGRect in SpriteKitSpriteKit中CGRect的原点
【发布时间】:2017-06-13 00:26:18
【问题描述】:

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

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

【问题讨论】:

    标签: swift sprite-kit sklabelnode


    【解决方案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 在它的大小调整后保持在它的位置一样。

    希望这会有所帮助!

    【讨论】:

    • 它根本没有改变任何东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多