Scaling font size to fit vertically in UILabel

前端 未结 2 1802
野的像风
野的像风 2021-02-02 13:00

I want to take a standard UILabel and increase the font size so that it fills the vertical space. Taking inspiration from the accepted answer for this question, I defined a sub

相关标签:
2条回答
  • 2021-02-02 13:24

    Your calculation for pointsPerPixel is the wrong way up, it should be...

    float pointsPerPixel =  self.font.pointSize / size.height;
    

    Also, maybe this code should be in layoutSubviews as the only time the font should be changed is when the frame size changes.

    0 讨论(0)
  • 2021-02-02 13:28

    I wonder if its a rounding error inching up to the next larger font size. Could you just scale the rec.size.height slightly? Something like:

    float desiredPointSize = rect.size.height *.90 * pointsPerPixel;
    

    Update: Your pointPerPixel calculation is backwards. You're actually dividing pixels by font points, instead of points by Pixels. Swap those and it works every time. Just for thoroughness, here's the sample code I tested:

    //text to render    
    NSString *soString = [NSString stringWithFormat:@"{Hg"];
    UIFont *soFont = [UIFont fontWithName:@"Helvetica" size:12];
    
    //box to render in
    CGRect rect = soLabel.frame;
    
    //calculate number of pixels used vertically for a given point size. 
    //We assume that pixel-to-point ratio remains constant.
    CGSize size = [soString sizeWithFont:soFont];
    float pointsPerPixel;
    pointsPerPixel = soFont.pointSize / size.height;   //this calc works
    //pointsPerPixel = size.height / soFont.pointSize; //this calc does not work
    
    //now calc which fontsize fits in the label
    float desiredPointSize = rect.size.height * pointsPerPixel;
    UIFont *newFont = [UIFont fontWithName:@"Helvetica" size:desiredPointSize];
    
    //and update the display
    [soLabel setFont:newFont];
    soLabel.text = soString;
    

    That scaled and fit inside the label box for every size I tested, ranging from 40pt to 60pt fonts. When I reversed the calculation, then I saw the same results with the font being too tall for the box.

    0 讨论(0)
提交回复
热议问题