let size = CGSize(width: 250, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let estimatedFrame = NSString(string: text).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 15)], context: nil)
func boundingRect(with size: CGSize, options: NSStringDrawingOptions = [], attributes: [String : Any]? = nil, context: NSStringDrawingContext?) -> CGRect
返回文本绘制所占据的矩形空间
size
宽高限制
options
文本绘制时的附加选项
context
context上下文。包括一些信息,例如如何调整字间距以及缩放。最终,该对象包含的信息将用于文本绘制。可为 nil
NSStringDrawingOptions
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 }
}
let text = "恨有多一点碰撞 仍然无聊事干不敢打搅对方 要是你愿意 诚实讲一趟 彼此都起码觉得释放 不要哭 我也忍得了这些年来的委屈 没法真心爱下去 只好真心真意的结束"
let size = CGSize(width: 250, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let estimatedFrame = NSString(string: text).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 15)], context: nil)
print("height:\(estimatedFrame.height),width:\(estimatedFrame.width)")
usesLineFragmentOrigin //文本将以每行组成的矩形为单位计算整个文本的尺寸(多行使用该参数,其他三个参数单行事使用)
height:89.501953125,width:248.7990234375
usesFontLeading //使用字体的行间距来计算文本占用的范围,即每一行的底部到下一行的底部的距离计算
height:17.900390625,width:250.0
usesDeviceMetrics //使用图像字形边界而不是排版边界。
height:14.055,width:1086.2521875
truncatesLastVisibleLine //如果文本超出指定的边界,截断并将省略号字符添加到上一个可见行。
height:17.900390625,width:250.0