【问题标题】:boundingRectForGlyphRange always returns rect for font size 12boundingRectForGlyphRange 始终返回字体大小为 12 的 rect
【发布时间】:2014-09-23 07:41:36
【问题描述】:

我正在尝试使用boundingRectForGlyphRange 方法计算单个字形的矩形。一切正常,除了它总是返回矩形,好像字体大小是 12。尽管我在属性字符串中将它设置为 20。

let font = UIFont.systemFontOfSize(20)
var attributedString = NSMutableAttributedString(string: text)
let range = NSRange(location: 0, length: countElements(text))
attributedString.addAttribute(NSFontAttributeName, value: font, range: range)


let textContainer = NSTextContainer()
textContainer.size = CGSize(width: 300, height: 100)
let layoutManager = NSLayoutManager()
let textStorage = NSTextStorage(string: attributedString.mutableString)

layoutManager.textStorage = textStorage
layoutManager.addTextContainer(textContainer)

let rect = layoutManager.boundingRectForGlyphRange(NSRange(location: 0, length: 1), inTextContainer: textContainer)

如何让它返回 rect 的文本大小 20 而不是 12?

【问题讨论】:

    标签: ios swift textkit


    【解决方案1】:

    只需将NSTextStorage 初始化为attributedString:

    let textStorage = NSTextStorage(attributedString: attributedString)
    

    而不是

    let textStorage = NSTextStorage(string: attributedString.mutableString)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-29
      • 2012-09-08
      • 1970-01-01
      相关资源
      最近更新 更多