How to make NSStringDrawingContext shrink text?

前端 未结 3 877
Happy的楠姐
Happy的楠姐 2021-02-04 08:10

I\'m trying to use the attributed string API of iOS 6 to calculate the size of text and shrink the font size if necessary. However, I can\'t get it to work as the documentation

3条回答
  •  醉梦人生
    2021-02-04 08:26

    Just wanted to post this solution as I have been battling with this for a couple hours. I could never get the text area to scale down and would always have the last lines of text cut off.

    The solution for me was to not add a context and just set it to nil. I got this when looking at the example on this site. https://littlebitesofcocoa.com/144-drawing-multiline-strings

    Note after getting the size the box would draw at using

    pageStringSize = [myString boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrsDictionary context:nil];
    

    I still needed to loop through scaling down the font manually:

    while (pageStringSize.size.height > 140 && scale > 0.5) {
                scale = scale - 0.1;
                font = [UIFont fontWithName:@"Chalkboard SE" size:24.0 *scale];
                attrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,[NSNumber numberWithFloat:1.0], NSBaselineOffsetAttributeName, nil];
    
                pageStringSize = [myString boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrsDictionary context:nil];
    
            }
    

提交回复
热议问题