IOS: finding the right font size to install in UILabel depending on its size

I have UILabelwhose property textI would like to set paragraphs of text to use NSString.

I have an array in which I store a sequence of characters that represent a text paragraph.

The paragraph should not fully comply / include in this UILabel. If the paragraph does not end, I will move on to the next shortcut.

Say, if I had the rectangular size of this UILabel160 X 240, how could I determine the correct font size to fill this line well UILabel?

Is there a mathematical way to calculate the font size based on the size of the rectangle on the screen?

For instance:

UILabel *aLabel = [[UIlabel alloc] initwithFrame(CGRect){{0, 0}, 160, 240}];
aLabel.font = [UIFont fontWithName:@"Courier New" size:<???>]; //(font unit in points)

NSMutableString *aString = [[NSMutableString alloc] init];

//The following tries to fit the character one by one within the label rect based on   
//the width and height of the UILabel by appending String
int index = 0;
for(int x = 0; x < 240; x+=<???>) //height of label (pixel unit)
{
    for(int y = 0; y < 160; y+=<???>) //width of label (pixel unit)
    {
        [aString appendWithString:[paragraphArray objectAtIndex:index]];
        index++;
    }
    [aString appendWithString:@\n"];  //line break
}
aLabel.text = aString;

, ??? ( , for)?

, , .

0
2
+(void)resizeFontForLabel:(UILabel*)aLabel{

    // use font from provided label so we don't lose color, style, etc
    UIFont *font = aLabel.font;

    float lblWidth = aLabel.frame.size.width;
    float lblHeight = aLabel.frame.size.height;

    CGFloat fontSize = [font pointSize];
    UIFont *newFont = font;
    TRC_DBG(@"%@", aLabel.text);
    CGFloat height = [aLabel.text sizeWithFont:font constrainedToSize:CGSizeMake(lblWidth,MAXFLOAT) lineBreakMode:aLabel.lineBreakMode].height;

    TRC_DBG(@"Label Height %f Constraint height %f", lblHeight, height);
    //Reduce font size while too large, break if no height (empty string)
    while (height > lblHeight && height != 0) {
        fontSize--;
        newFont = [UIFont fontWithName:font.fontName size:fontSize];
        height = [aLabel.text sizeWithFont:newFont constrainedToSize:CGSizeMake(lblWidth,MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping].height;
        TRC_DBG(@"Constrained Height %f", height);
    };


    TRC_DBG(@"Font size before adjustment %f", aLabel.font.pointSize);
    // Set the UILabel font to the newly adjusted font.
    aLabel.font = newFont;
    TRC_DBG(@"Adjust to font size of %f", newFont.pointSize);
    [aLabel setNeedsLayout];
}
+1

, .

0

All Articles