我正在尝试使用iOS 6的归属字符串API来计算文本的大小,并在必要时缩小字体大小.但是,如文档所述,我无法使其正常工作.
NSString *string = @"This is a long text that doesn't shrink as it should"; NSStringDrawingContext *context = [NSStringDrawingContext new]; context.minimumScaleFactor = 0.5; UIFont *font = [UIFont fontWithName:@"SourceSansPro-Bold" size:32.f]; NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new]; paragraphStyle.lineBreakMode = NSLineBreakByClipping; NSDictionary *attributes = @{ NSFontAttributeName: font,NSParagraphStyleAttributeName: paragraphStyle }; NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:self.title attributes:attributes]; CGRect rect = [attributedString boundingRectWithSize:CGSizeMake(512.f,512.f) options:NSStringDrawingUsesLineFragmentOrigin context:context]; NSLog(@"rect: %@,context: %@",NSStringFromCGRect(rect),context.debugDescription);
但文本不缩小并被截断. actualScaleFactor始终为1.日志结果为:
rect:{{0,0},{431.64801,80.447998}},context:<NSStringDrawingContext: 0x14e85770> minimumScaleFactor:0.500000 minimumTrackingAdjustment:0.000000 actualScaleFactor:1.000000 actualTrackingAdjustment:0.000000 totalBounds:{{0,80.447998}}
如果我使用实际的绘图方法而不是测量方法,结果是一样的.如果我删除段落样式,它会使文本包装并且不缩小.如果我删除段落样式,我选择一个只允许一行文本的大小,文本也被截断,而不是缩小.哪里不对?有很少的文档或在线资源处理NSStringDrawingContext.而且我试图避免使用sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:在iOS 7中已被弃用.
解决方法
NSStringDrawingContext的minimumScaleFactor在iOS 7中显示为破坏.
就我可以做出来,即使在iOS 6中,它也无法画画;它有助于测量,所以你可以解决在它像绘图一样工作的上下文中会发生什么,如UILabel.这样,你知道标签的正确最小高度.
或者,您可以使用生成的比例因子来缩小文本,这在现在知道它将适合.
例:
- (void)drawRect:(CGRect)rect { // rect is 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]; }
在iOS 6中,缩放比例大约为0.85,您可以使用它来缩小文本.但是在iOS 7中,规模保持在1,表明没有收缩,NSStringDrawingContext的这个功能现在没有用.我不知道这是一个错误还是该功能是否被故意放弃.