我正在尝试使用 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, 0}, {431.64801, 80.447998}}
如果我使用实际绘图方法而不是测量方法,结果是相同的。如果我删除段落样式,它会使文本换行并且不会缩小它。如果我删除段落样式并选择只允许一行文本的大小,则文本也会被截断而不是缩小。怎么了?很少有文档或在线资源处理NSStringDrawingContext
. 而且我试图避免使用sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:
iOS 7 中已弃用的内容。