How to make NSStringDrawingContext shrink text?

前端 未结 3 882
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:19

    NSStringDrawingContext's minimumScaleFactor appears to be broken in iOS 7.

    As far as I can make out, even in iOS 6, it didn't work for drawing; it worked for measuring, so you could work out what would happen in a context where it does work for drawing, like a UILabel. That way, you know the correct minimum height for the label.

    Or, you could use the resulting scale factor to shrink the text yourself, in the knowledge that now it will fit.

    Example:

    - (void)drawRect:(CGRect)rect
    {
        // rect is 0,0,210,31
    
        NSMutableAttributedString* s = 
            [[NSMutableAttributedString alloc] initWithString: @"This is the army Mister Jones."];
        [s addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"GillSans" size:20]} 
            range:NSMakeRange(0,s.length)];
    
        NSMutableParagraphStyle* para = [[NSMutableParagraphStyle alloc] init];
        para.lineBreakMode = NSLineBreakByTruncatingTail;
        [s addAttributes:@{NSParagraphStyleAttributeName:para} 
            range:NSMakeRange(0,s.length)];
    
        NSStringDrawingContext* con = [[NSStringDrawingContext alloc] init];
        con.minimumScaleFactor = 0.5;
    
        CGRect result = 
            [s boundingRectWithSize:rect.size 
                options:NSStringDrawingUsesLineFragmentOrigin context:con];
        CGFloat scale = con.actualScaleFactor;
        // ...(could have a check here to see if result fits in target rect)...
    
        // fix font to use scale factor, and draw
        [s addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"GillSans" size:20*scale]} 
            range:NSMakeRange(0,s.length)];
        [s drawWithRect:rect options:NSStringDrawingUsesLineFragmentOrigin context:nil];
    
    }
    

    In iOS 6, scale is about 0.85 and you can use it as shown to shrink the text. But in iOS 7, scale remains at 1, suggesting that no shrinkage is happening and this feature of NSStringDrawingContext is now useless. I can't tell whether that's a bug or whether the feature has been deliberately abandoned.

提交回复
热议问题