iOS7弃用了NSString的drawAtPoint:forWidth:withFont:minFontSize:actualFontSize:lineBreakMode:baselineAdjustment:

Rob*_*Rob 11 objective-c deprecated nsstring ios ios7

在iOS7的发布中,以下函数已被弃用:

drawAtPoint:forWidth:withFont:minFontSize:actualFontSize:lineBreakMode:baselineAdjustment:
Run Code Online (Sandbox Code Playgroud)

在Apple的文档中,它建议使用

drawInRect:withAttributes:
Run Code Online (Sandbox Code Playgroud)

我使用这个函数的原因是因为<code>minFontSize</code>参数,它让我在rect中绘制一个字符串.如果文本不适合,它将首先缩小文本大小<code>minFontSize</code>,然后如果它不适合,它将截断它.到目前为止,我无法完成此任务<code>drawInRect:withAttributes:</code>

任何人都可以帮我确定哪个键可以用来确定<code>minFontSize</code>等价物?

谢谢!

-抢

Flo*_*ian 12

它比以前复杂一点,你不能使用最小字体大小,但必须使用最小字体比例因子.iOS SDK中还有一个错误,它在大多数用例中都会破坏它(请参阅底部的注释).这是你要做的:

// Create text attributes
NSDictionary *textAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:18.0]};

// Create string drawing context
NSStringDrawingContext *drawingContext = [[NSStringDrawingContext alloc] init];
drawingContext.minimumScaleFactor = 0.5; // Half the font size

CGRect drawRect = CGRectMake(0.0, 0.0, 200.0, 100.0);
[string drawWithRect:drawRect
             options:NSStringDrawingUsesLineFragmentOrigin
          attributes:textAttributes
             context:drawingContext];
Run Code Online (Sandbox Code Playgroud)

笔记:

  • iOS 7 SDK中似乎存在至少版本7.0.3的错误:如果在属性中指定自定义字体,则忽略miniumScaleFactor.如果为属性传递nil,则正确缩放文本.

  • NSStringDrawingUsesLineFragmentOrigin选项是非常重要的.它告诉文本绘图系统,绘图rect的原点应该在左上角.

  • 无法使用新方法设置baselineAdjustment.您必须先通过boundingRectWithSize:options:attributes:context:先调用然后调整矩形然后再将其传递给自己drawWithRect:options:attributes:context.