How to make NSStringDrawingContext shrink text?

前端 未结 3 880
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:21

    After googling for a long time I did not find a solution working under iOS7. Right now I use the following workaround, knowing that it is very ugly. I render a UILabel in memory, take a screenshot and draw that. UILabel is able to shrink the text correctly.

    But perhaps someone finds it useful.

        UILabel *myLabel = [[UILabel alloc] initWithFrame:myLabelFrame];
        myLabel.font = [UIFont fontWithName:@"HelveticaNeue-BoldItalic" size:16];
        myLabel.text = @"Some text that is too long";
        myLabel.minimumScaleFactor = 0.5;
        myLabel.adjustsFontSizeToFitWidth = YES;
        myLabel.backgroundColor = [UIColor clearColor];
    
        UIGraphicsBeginImageContextWithOptions(myLabelFrame.size, NO, 0.0f);
        [[myLabel layer] renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        [screenshot drawInRect:myLabel.frame];
    

提交回复
热议问题