2015-06-22 53 views

回答

25

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); 
} 
+0

有人可以添加objC此代碼。謝謝。 – GeneCode

+0

請注意,您可能需要在標籤節點和矩形之間進行附加填充。 'MIN(rect.size.width /(labelNode.frame.size.width + PADDING),rect.size.height /(labelNode.frame.size.height + PADDING));'' – Wouter

1

我已經寫這個寬度,但你可以適應它的高度,以適應你的CGRect。在這個例子中,pg是一個用你正在使用的字體初始化的SKLabelNode。參數是你的字符串和目標寬度,結果是你想要分配給你的SKLabelNode的大小。當然,你也可以直接放你的SKLabelNode。如果尺寸太大,那麼最大尺寸是50,但這是個人的。

func getTextSizeFromWidth(s:String, w:CGFloat)->CGFloat { 

    var result:CGFloat = 0; 
    var fits:Bool = false 
    pg!.text=s 
    if(s != ""){ 
     while (!fits) { 
     result++; 
     pg!.fontSize=result 
     fits = pg!.frame.size.width > w; 
     } 
    result -= 1.0 
    }else{ 
     result=0; 
    } 

    return min(result, CGFloat(50)) 
} 

編輯:其實,我才意識到我也寫了這一點:

extension SKLabelNode { 
func fitToWidth(maxWidth:CGFloat){ 
    while frame.size.width >= maxWidth { 
     fontSize-=1.0 
    } 
} 

func fitToHeight(maxHeight:CGFloat){ 
    while frame.size.height >= maxHeight { 
     fontSize-=1.0 
    }