Last active
August 23, 2019 06:28
-
-
Save a2/abdcb6b6a684b8bf2df16d348092a0f7 to your computer and use it in GitHub Desktop.
Tibetan characters cause NSLayoutManager to return incorrect bounding rect (rdar://48745247)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Incorrect and correct bounding rects