Nour
Nour

Reputation: 343

How to center the text inside the SkLabelNode

I do not mean this one: Label.horizontalAlignmentMode = SKLabelNode HorizontalAlignmentModeCenter

Or Label.verticalAlignmentMode =

Upvotes: 3

Views: 891

Answers (1)

Confused
Confused

Reputation: 6278

SKLabelNodes are very primitive renderings of simplistic, barely editable text to bitmaps, and thrown up as such on the screen. They're not meant to solve big design problems.... so they don't have any awareness of their "frame".

Having said that... they are a subclass of SKNode, which has a frame property, but that's not like how you think of frames within design applications or page writing apps or anything else... from the docs, it's this, of a node:

The frame is the smallest rectangle that contains the node’s content, taking into account the node’s xScale, yScale, and zRotation properties. Not all nodes contain content of their own.

This can be useful, cause it's got some convenient getters. You can get the width, height, maxX and maxY and minX and minY and midX and midY, too.

So you could, theoretically, use these to help you centre the text content relative to something else based on these convenience numbers of the frame your text label takes up in the scene.

But that wouldn't be fun.

Instead, you can create a dummy SKSpriteNode of exactly the same dimensions as the text, fill it with SKColor.clear so it can't be seen and costs you nothing in rendering terms, and then add your text node to this dummy SKSpriteNode, as a child of it.

Now you have the origin (anchor point) of the SKSpriteNode to use as your guide to positioning the text node anywhere you like, and whenever you change the size of the text, use a willSet to resize your SKSpriteNode to match it. This way your origin/anchor will always work as you want.

There are brighter minds here that can come up with far better ways to do this sort of thing, but this is the kind of hack I'm used to doing in 3D design apps to get text to behave well.

Upvotes: 1

Related Questions