How to calculate multi-lines String’s height ?
使用的具体方法
extension NSString {
@available(iOS 7.0, *)
open func draw(with rect: CGRect, options: NSStringDrawingOptions = [], attributes: [NSAttributedString.Key : Any]? = nil, context: NSStringDrawingContext?)
@available(iOS 7.0, *)
open func boundingRect(with size: CGSize, options: NSStringDrawingOptions = [], attributes: [NSAttributedString.Key : Any]? = nil, context: NSStringDrawingContext?) -> CGRect
}
参数说明
size
The size of the rectangle to draw in. 绘制String的矩形区域大小
options
String drawing options. 字符串绘制选项
具体Enum值如下(Objective-C中是以枚举来实现)
@available(iOS 6.0, *)
public struct NSStringDrawingOptions : OptionSet {
public init(rawValue: Int)
public static var usesLineFragmentOrigin: NSStringDrawingOptions { get }
public static var usesFontLeading: NSStringDrawingOptions { get }
public static var usesDeviceMetrics: NSStringDrawingOptions { get }
@available(iOS 6.0, *)
public static var truncatesLastVisibleLine: NSStringDrawingOptions { get }
}
想要理解上面4个值的含义决非易事,文档好像什么都说了,又好像什么也没说。。。
attributes
A dictionary of text attributes to be applied to the string. These are the same attributes that can be applied to an NSAttributedString object, but in the case of NSString objects, the attributes apply to the entire string, rather than ranges within the string. 同属性字符串
context
The string drawing context to use for the receiver, specifying minimum scale factor and tracking adjustments. 从来没用过,传nil.
注意点
官方说明
To correctly draw and size multi-line text, pass usesLineFragmentOrigin in the options parameter. This method returns fractional sizes (in the size component of the returned CGRect); to use a returned size to size views, you must raise its value to the nearest higher integer using the ceil function. This method returns the actual bounds of the glyphs in the string. Some of the glyphs (spaces, for example) are allowed to overlap the layout constraints specified by the size passed in, so in some cases the width value of the size component of the returned CGRect can exceed the width value of the size parameter.
- 计算多行String, 一定要添加
usesLineFragmentOrigin 选项; - 计算绘制String所需的高度,一定要用
ceil 包裹,也就是需要向上取整;
show a demo code
let floatHeight = "hello boundingRect".boundingRect(with: CGSize(width: UIScreen.main.bounds.size.width - 32, height: CGFloat(MAXFLOAT)), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font: UIFont(name: "PingFangSC-Light", size: 20)!], context: nil).size.height
let height = ceil(floatHeight)
|