Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaling UIFont size relative to screen size

Tags:

ios

iphone

uifont

I'm letting users add a UITextField on top of their images like a caption.

I've designed it so that their images are all perfect squares according to their iPhone screen size. So on my iPhone 5S, it would be a 320x320 UIImageView. An iPhone 6 would be 375x375 UIImageView. Images posted by larger screen phones would be scaled down by the imageView when viewing in the smaller phone.

How do I setup a font size that will be relative to screen width?

I'm currently using:

[UIFont systemFontOfSize:16.0]

Would it be appropriate to use this?:

[UIFont systemFontOfSize:self.frame.size.width/20];

I'm not sure what point size actually represents in a font size. I've also found [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; but I'm not sure if this is what I'm looking for.

Thanks

like image 865
user339946 Avatar asked Oct 20 '22 22:10

user339946


2 Answers

UIFont has a method which gets you the system font size. You can then use that to dynamically compute a reasonable font size. What is reasonable will be up to you to test and experiment with. That would lead to something like this:

UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]*[UIScreen mainScreen].bounds.width/375.0];
like image 186
Rick Avatar answered Nov 03 '22 21:11

Rick


It's a bit overkill, but to get sure my text fits on the screen i am doing a loop to find out the font size (because i am rendering this text in a custom drawRect implementation (there might be a better way if you are using UILabel)

    float FACTOR = 0.5f;
    UIFont *font = [UIFont fontWithName:_fontName size:_maximumSize];
    // paragraph for both
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment     = NSTextAlignmentCenter;
    // attributes for back
    NSDictionary *attributes = @{NSFontAttributeName            : font,
                                 NSParagraphStyleAttributeName  : paragraphStyle};
    CGSize textSize   = [_text sizeWithAttributes:attributes];
    // reduce font size until the text fits in bounds
    while(textSize.width > _view.bounds.size.width * FACTOR || textSize.height > _view.bounds.size.height * FACTOR)
    {
        _maximumSize--;
        font       = [font fontWithSize:_maximumSize];
        attributes = @{NSFontAttributeName            : font,
                       NSParagraphStyleAttributeName  : paragraphStyle};
        textSize   = [_progressText sizeWithAttributes:attributes];
    }

Simply adjust the FACTOR to make the font fit relative to the views bounds.

like image 45
Martin Mlostek Avatar answered Nov 03 '22 20:11

Martin Mlostek