Ios NSLayoutManager、BoundingRectfolyPhrange和表情符号
我正在使用Ios NSLayoutManager、BoundingRectfolyPhrange和表情符号,ios,swift,nslayoutmanager,Ios,Swift,Nslayoutmanager,我正在使用NSAttributedString的drawInRect(rect:CGRect)方法显示可能包含表情符号的文本。因为我想检测文本上的点击,所以我使用以下方法查看点击了哪个字符: let textStorage = NSTextStorage(attributedString: attributedString) let layoutManager = NSLayoutManager() layoutManager.usesFontLeading = true textStorage
NSAttributedString
的drawInRect(rect:CGRect)
方法显示可能包含表情符号的文本。因为我想检测文本上的点击,所以我使用以下方法查看点击了哪个字符:
let textStorage = NSTextStorage(attributedString: attributedString)
let layoutManager = NSLayoutManager()
layoutManager.usesFontLeading = true
textStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer(size: containerSize)
layoutManager.addTextContainer(textContainer)
textContainer.lineFragmentPadding = 0.0
layoutManager.ensureLayoutForTextContainer(textContainer)
let tappedIndex = layoutManager.characterIndexForPoint(point,
inTextContainer: textContainer,
fractionOfDistanceBetweenInsertionPoints: nil)
这提供了正确的索引,在我开始向文本添加表情符号之前,我可以使用它。一旦添加表情符号,就开始出现检测偏移。这让我看到了我正在寻找的字形的边界矩形。我注意到表情符号的边框太大了。我设置了以下测试用例来检查差异:
let emojiText = "I have solved the issue. It appears that NSAttributedString.drawInRect
draws differently from CoreText
. I now use the following code to draw the text in drawRect
:
let totalRange = layoutManager.glyphRangeForTextContainer(textContainer)
layoutManager.drawBackgroundForGlyphRange(range, atPoint: CGPointZero)
layoutManager.drawGlyphsForGlyphRange(range, atPoint: CGPointZero)
let emojiText=“我已经解决了这个问题。似乎nsattributed string.drawInRect
的绘制方式与CoreText
不同。我现在使用以下代码在drawRect
中绘制文本: