如何设置SKLabelNode的字体大小以适合固定大小(Swift) [英] How to set font size of SKLabelNode to fit in fixed size (Swift)

查看:174
本文介绍了如何设置SKLabelNode的字体大小以适合固定大小(Swift)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有SKLabelNode的正方形(200X200).标签显示得分,并且我可以达到一个很大的数字.我想把这个数字放在正方形里.

I have a square (200X200) with a SKLabelNode in it. The label shows score and it my be reach a large number. I want fit the number in the square.

如何更改SKLabelNode的文本大小(或大小)以使其适合固定大小.

How can i change text size (or Size) of a SKLabelNode to fit it in a fixed size.

推荐答案

可以将SKLabelNode的框架大小与给定的矩形进行比较.如果按标签矩形和所需矩形的大小成比例缩放字体,则可以确定最佳字体大小以尽可能地填充空间.最后一行方便地将标签移动到矩形的中心. (如果文本只是小写字母或标点符号之类的短字符,则可能看起来偏心.)

The size of the frame of the SKLabelNode can be compared against the given rectangle. If you scale the font in proportion to the sizes of the label's rectangle and the desired rectangle, you can determine the best font size to fill the space as much as possible. The last line conveniently moves the label to the center of the rectangle. (It may look off-center if the text is only short characters like lowercase letters or punctuation.)

快速

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

这篇关于如何设置SKLabelNode的字体大小以适合固定大小(Swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆