2017-06-13 4 views
1

特定のサイズのシーンの中央にテキストを中央に配置しようとしています。SpriteKitのCGRectの起点

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使用:特定のサイズにSKNodeLabelのサイズを調整するには

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

を。しかし、私はそのラベルの原点をスクリーンの中心にしたいので、アンカーポイントが0.5、0.5であるので(0,0)。しかし、私はこれを取得:)adjustLabelFontSizeToFitRect(

enter image description here

をこのです:

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

horizontalAlignmentModeとSKLabelNodeのverticalAlignmentModeを見てください。これは、ラベルの「アンカーポイント」のようなもので、SKLabelNode内のテキストの水平および垂直の位置を調整するために使用できます。

デフォルトでは、verticalAlignmentModeは.baselineに設定され、horizontalAlignmentModeは.centerに設定されています。だから、「起源」はラベルのちょうど中央(中央、中央)ではありません。

これはあなたが探している効果である場合には分からないのですが、あなたはラベルがシーンの中心にしたい場合は、私はちょうどaddCubeExperienceLabel方法でこれらの行を追加します。

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

スクリーンの中央に開始のテキストを表示する場合は、horizo​​ntalAlignmentModeを.leftに設定します。現在、テキストの中心は画面の中央にあります。

ラベルの位置はaddCubeExperienceLabelであり、adjustLabelFontSizeToFitRectではないことに注意してください。ラベルのフォントサイズを調整すると、通常のSKSpriteNodeのサイズが調整された後の位置と同じように、ラベルのフォントサイズはその位置に維持されます。

希望すると便利です。

+0

何も変更されていません – Pablo