随着 iOS7 的发布,以下功能已被弃用:
drawAtPoint:forWidth:withFont:minFontSize:actualFontSize:lineBreakMode:baselineAdjustment:
在 Apple 的文档中建议使用
drawInRect:withAttributes:
我使用这个函数的原因是因为 <code>minFontSize</code>
参数,它让我可以在矩形内绘制一个字符串。
如果文本不适合,它会先将文本大小缩小到 <code>minFontSize</code>
然后如果它不适合,它会截断它。
到目前为止,我无法使用 <code>drawInRect:withAttributes:</code>
完成此操作.
我可以使用哪个 key 来确定 <code>minFontSize</code>
等价?
最佳答案
它比以前复杂一点,你不能使用最小字体大小,但必须使用最小字体比例因子。 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];
注意事项:
至少在 7.0.3 版之前的 iOS 7 SDK 中似乎存在错误:如果您在属性中指定自定义字体,则 miniumScaleFactor 将被忽略。如果您为属性传递 nil,则文本会正确缩放。
NSStringDrawingUsesLineFragmentOrigin
选项很重要。它告诉文本绘图系统,绘图矩形的原点应该在左上角。无法使用新方法设置 baselineAdjustment。您必须自己执行此操作,首先调用
boundingRectWithSize:options:attributes:context:
,然后在将其传递给drawWithRect:options:attributes:context
之前调整矩形。
关于iOS 7's deprecation of NSString' s drawAtPoint :forWidth:withFont:minFontSize:actualFontSize:lineBreakMode:baselineAdjustment:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18923349/