【发布时间】:2013-12-26 10:41:17
【问题描述】:
我有一些文本,我正在通过 NSAttributedString(下面的代码)将它们绘制到固定框架中。目前我正在将文本大小硬编码为 16。我的问题是,有没有办法计算给定框架的文本的最佳拟合大小?
- (void)drawText:(CGContextRef)contextP startX:(float)x startY:(float)
y withText:(NSString *)standString
{
CGContextTranslateCTM(contextP, 0, (bottom-top)*2);
CGContextScaleCTM(contextP, 1.0, -1.0);
CGRect frameText = CGRectMake(1, 0, (right-left)*2, (bottom-top)*2);
NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:standString];
[attrString addAttribute:NSFontAttributeName
value:[UIFont fontWithName:@"Helvetica-Bold" size:16.0]
range:NSMakeRange(0, attrString.length)];
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)(attrString));
struct CGPath * p = CGPathCreateMutable();
CGPathAddRect(p, NULL, frameText);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0,0), p, NULL);
CTFrameDraw(frame, contextP);
}
【问题讨论】:
-
这个自定义的 UILabel 正在使用这个。我认为这可以帮助https://github.com/vigorouscoding/KSLabel
-
我没有使用 UILabel,因为它们必须是方形的 - 这是被绘制成 Quartz 2D 创建形状的文本。
-
UILabels 可以是方形的吗?
-
@GuybrushThreepwood - 看我的回答。这确实是一个简单快速的解决方案。
标签: ios objective-c fonts core-text nsattributedstring