可以将SKLabelNode的框架的大小与给定的矩形进行比较.如果按照标签的矩形和所需的矩形的大小成比例缩放字体,则可以确定尽可能多填充空间的最佳字体大小.最后一行方便地将标签移动到矩形的中心. (如果文本只是小写字母或标点符号的短字符,则可能会偏离中心).
迅速
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) }
Objective-C的
-(void)adjustLabelFontSizeToFitRect:(SKLabelNode*)labelNode rect:(CGRect)rect { // Determine the font scaling factor that should let the label text fit in the given rectangle. double scalingFactor = MIN(rect.size.width / labelNode.frame.size.width,rect.size.height / labelNode.frame.size.height); // Change the fontSize. labelNode.fontSize *= scalingFactor; // Optionally move the SKLabelNode to the center of the rectangle. labelNode.position = CGPointMake(CGRectGetMidX(rect),CGRectGetMidY(rect) - labelNode.frame.size.height / 2.0); }