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
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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With