iosswiftsprite-kitsklabelnode

SpriteKit SKLabelNode alignment


I am trying to get center some text at the center of the scene with a specific size.

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

So I use the adjustLabelFontSizeToFitRect:

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

To adjust the size of the SKNodeLabel to a specific size. But I want the origin of that label to be the center of the screen, so (0,0), since the anchor point is 0.5, 0.5. However, I get this:

enter image description here

The adjustLabelFontSizeToFitRect() is this:

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

Solution

  • Have a look at the horizontalAlignmentMode and the verticalAlignmentMode of an SKLabelNode. It is sort of like an "anchor point" for labels and can be used to adjust the horizontal and vertical positions of text within an SKLabelNode.

    By default, verticalAlignmentMode is set to .baseline, and horizontalAlignmentMode is set to .center. So the "origin" is not exactly at (center, center) of the label.

    Don't know if this is the effect you're looking for, but if you want the label to be centered in the scene, I would just add these lines in the addCubeExperienceLabel method:

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

    Set horizontalAlignmentMode to .left if you want the text to start at the center of the screen. Right now the center of the text is at the center of the screen.

    Note that position of the label is set in addCubeExperienceLabel and not in adjustLabelFontSizeToFitRect. If you adjust the label's font size, it should still remain at its position, just like a normal SKSpriteNode remains in its position after its size is adjusted.

    Hope this helps!