Skip to content

Instantly share code, notes, and snippets.

@a2
Last active August 23, 2019 06:28
Show Gist options
  • Save a2/abdcb6b6a684b8bf2df16d348092a0f7 to your computer and use it in GitHub Desktop.
Save a2/abdcb6b6a684b8bf2df16d348092a0f7 to your computer and use it in GitHub Desktop.
Tibetan characters cause NSLayoutManager to return incorrect bounding rect (rdar://48745247)
let string = "If the Tibetan characters དོམ་ཁྲ are removed, then the function boundingRect(forGlyphRange:in:) returns the correct value. Note that the values are incorrect for any range in a paragraph containing these characters."
let textStorage = NSTextStorage(string: string)
textStorage.addAttribute(.font, value: UIFont.systemFont(ofSize: UIFont.labelFontSize), range: NSRange(0 ..< textStorage.length))
// Xcode in dark mode makes the text hard to read.
textStorage.addAttribute(.foregroundColor, value: UIColor.white, range: NSRange(0 ..< textStorage.length))
let textContainer = NSTextContainer(size: CGSize(width: 300, height: 300))
let layoutManager = NSLayoutManager()
layoutManager.addTextContainer(textContainer)
textStorage.addLayoutManager(layoutManager)
let characterRange = string.range(of: "If the Tibetan characters")!
let glyphRange = layoutManager.glyphRange(forCharacterRange: NSRange(characterRange, in: string), actualCharacterRange: nil)
let boundingRect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer)
let offset: CGFloat = 10
let renderer = UIGraphicsImageRenderer(size: CGSize(width: textContainer.size.width + 2 * offset, height: textContainer.size.height + 2 * offset))
let image = renderer.image { context in
let glyphRange = NSRange(0 ..< layoutManager.numberOfGlyphs)
let origin = CGPoint(x: offset, y: offset)
layoutManager.drawBackground(forGlyphRange: glyphRange, at: origin)
layoutManager.drawGlyphs(forGlyphRange: glyphRange, at: origin)
UIColor.red.set()
UIRectFrame(boundingRect.offsetBy(dx: offset, dy: offset))
}
@dennda
Copy link

dennda commented Aug 22, 2019

Don't suppose you found a fix?

@a2
Copy link
Author

a2 commented Aug 23, 2019

@dennda Unfortunately not. No reply on the bug report either :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment