使用 Swift,我想在 UILabel 中的 draw#rect 中获取字形的 boundingRect。
UILabel 已经具有大小(例如示例中的 300x300)和质量,例如居中的文本。
class RNDLabel: UILabel {
override func draw(_ rect: CGRect) {
let manager = NSLayoutManager()
let store = NSTextStorage(attributedString: NSAttributedString(
string: text!,
attributes: [NSAttributedString.Key.font: font]))
store.addLayoutManager(manager)
let textContainer = NSTextContainer(size: rect.size)
// note, intrinsicContentSize is identical there, no difference
manager.addTextContainer(textContainer)
let glyphRange = manager.glyphRange(
forCharacterRange: NSRange(location: 0, length: 1),
actualCharacterRange: nil)
let glyphRect = manager.boundingRect(
forGlyphRange: glyphRange, in: textContainer)
print("glyphRect \(glyphRect)")
...context?.addRect(glyphRect), context?.drawPath(using: .stroke)
super.draw(rect)
}
绿色方块不正确——它应该更像这些红色方块!
似乎有很多问题:
当然,我制作的 layoutManager 应该具有 UILabel 的品质,例如“居中文本”?(不过,我相信您实际上不能直接访问 UILabel 的 layoutManager 吗?)
我们应该使用 CTLineGetOffsetForStringIndex 之类的东西吗?在draw#rect中甚至可能吗
请注意,除了没有正确的偏移量外,绿框似乎还是错误的高度。(它看起来更像是一个普通的旧的 intrinsicContentSize 而不是字形边界框。)
如何?
作为记录,我的总体目标是根据实际的字形框移动字形(对于“y”、“X”等当然是不同的)。但总的来说,有很多有用的理由来了解字形的框。