How to set font size of SKLabelNode to fit in fixed size (Swift)

后端 未结 3 960
野性不改
野性不改 2020-12-29 06:21

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.

How c

3条回答
  •  庸人自扰
    2020-12-29 06:30

    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.)

    Swift

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

提交回复
热议问题