计算字体大小以适应框架 - 核心文本 - NSAttributedString - iOS [英] Calculate Font Size to Fit Frame - Core Text - NSAttributedString - iOS

查看:145
本文介绍了计算字体大小以适应框架 - 核心文本 - NSAttributedString - iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些文本是通过NSAttributedString(下面的代码)绘制成一个固定的框架。目前,我很难将文本大小编码为16.我的问题是,有没有一种方法来计算给定帧的文本的最佳拟合大小?



<$ p ($)$($)$($)$($)$($)$ 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-Boldsize: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);
}


解决方案

这是可能的是有一个系统运行的大小计算,然后调整大小,并重复,直到找到合适的大小。

Ie建立一个在一定大小之间的平分算法。

运行它的大小10.
太小。
大小20.
太小。
大小30.
太大。
大小25.
太小。
大小27.
恰到好处,使用大小27。

您甚至可以从数百个开始。



大小100.
太大。
大小50.
等...


I have some text which I am drawing into a fixed frame via an NSAttributedString (code below). At the moment I am hard coding the text size to 16. My question is, is there a way to calculate the best fit size for the text for the given frame ?

- (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);
}

解决方案

The only way I can see this being possible is to have a system that runs the size calculation then adjusts the size and repeats until it finds the right size.

I.e. set up a bisecting algorithm that goes between certain sizes.

i.e. run it for size 10. Too small. Size 20. Too small. Size 30. Too big. Size 25. Too small. Size 27. Just right, use size 27.

You could even start in hundreds.

Size 100. Too big. Size 50. etc...

这篇关于计算字体大小以适应框架 - 核心文本 - NSAttributedString - iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆