我有一些文本,我正在绘制成一个固定的框架通过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);
}
发布于 2013-12-09 19:02:47
我认为唯一可能的方法是让系统运行大小计算,然后调整大小并重复,直到找到合适的大小。
即,设置介于特定大小之间的二等分算法。
例如,运行它的大小为10。太小了。20号,太小了。30码。太大了。25码。太小了。27码。恰到好处,使用27码。
你甚至可以从几百个开始。
100号的。太大了。50码。等等。
发布于 2014-10-03 23:06:48
下面是一段简单的代码,它将计算出适合框架边界的最大字体大小:
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.text = @"Some text";
float largestFontSize = 12;
while ([label.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:largestFontSize]}].width > modifierFrame.size.width)
{
largestFontSize--;
}
label.font = [UIFont systemFontOfSize:largestFontSize];
发布于 2016-09-29 02:16:57
一个小技巧有助于使用sizeWithAttributes:
,而不需要迭代以获得正确的结果:
NSSize sampleSize = [wordString sizeWithAttributes:
@{ NSFontAttributeName: [NSFont fontWithName:fontName size:fontSize] }];
CGFloat ratio = rect.size.width / sampleSize.width;
fontSize *= ratio;
确保样本的fontSize
足够大,以获得良好的结果。
https://stackoverflow.com/questions/20468641
复制相似问题