首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >SpriteKit SKLabelNode对准

SpriteKit SKLabelNode对准
EN

Stack Overflow用户
提问于 2017-06-13 00:26:18
回答 1查看 693关注 0票数 2

我正试图在场景的中心得到一些特定大小的文本。

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
adjustLabelFontSizeToFitRect(labelNode: price, rect: CGRect(origin: CGPoint(x: 0, y: 0), size : buttonSize))

若要将SKNodeLabel的大小调整为特定大小,请执行以下操作。但是我希望标签的来源是屏幕的中心,所以(0,0),因为锚点是0.5,0.5。然而,我明白这一点:

adjustLabelFontSizeToFitRect()是这样的:

代码语言:javascript
运行
复制
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)
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-13 04:25:57

看看horizontalAlignmentModeverticalAlignmentMode of a SKLabelNode。它有点像标签的“锚点”,可以用来调整SKLabelNode中文本的水平和垂直位置。

默认情况下,verticalAlignmentMode设置为.baseline,horizontalAlignmentMode设置为.center。因此,“原产地”并不完全是在标签的(中心,中心)。

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

代码语言:javascript
运行
复制
price.position = CGPoint.zero
price.verticalAlignmentMode = .center 
price.horizontalAlignmentMode = .center  

如果希望文本从屏幕中心开始,请将horizontalAlignmentMode设置为.left。现在,文本的中心在屏幕的中心。

注意,标签的位置在addCubeExperienceLabel中设置,而不是在adjustLabelFontSizeToFitRect中设置。如果您调整标签的字体大小,它应该仍然保持在它的位置,就像一个普通的SKSpriteNode在调整它的大小后保持在它的位置一样。

希望这能有所帮助!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44510596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档