2016-07-27 9 views
3

NSAttributedStringdrawInRect(rect: CGRect) 메서드를 사용하여 그림이 포함 된 그림이 표시됩니다. 나는 텍스트에 탭을 감지 할 때부터 도청 된 문자를 확인하기 위해 다음과 같은 방법을 사용하십시오NSLayoutManager, boundingRectForGlyphRange 및 그림 이모시

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 = "" 
let font = UIFont.systemFontOfSize(20.0) 
let containerSize = CGSize(width: 300.0, height: 20000.0) 

let attributedString = NSAttributedString(string: emojiText, attributes: [NSFontAttributeName: font]) 

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 glyphRect = layoutManager.boundingRectForGlyphRange(NSRange(location: 0, length: attributedString.length), inTextContainer: textContainer) 
let boundingRect = attributedString.boundingRectWithSize(containerSize, options:[.UsesLineFragmentOrigin, .UsesFontLeading], context: nil) 

다음 CGRect들 결과 :

glyphRect = (0.0, 0.0, 23.0, 28.875) 
boundingRect = (0.0, 0.0, 23.0, 23.8671875) 

이것이 의미하는 것은이 두 가지 방법이 개 완전히 다른 크기를 제공한다는 것이다 나는 차이를 확인하려면 다음 테스트 케이스를 설정! 이것은 문제가되지 않지만 '오프셋'스택이 더 많은 줄로 나타납니다.

Example of the stacked offset

가 나는 characterIndexForPoint이 내게 준 문자 보라색 배경을 설정 boundingRectForGlyphRange의 녹색 개요를 RECT을주고 노란색 점은 실제 taplocation입니다. 녹색 사각형은 다른 문자와 잘 어울립니다. 그러나이 특별한 경우에는 잘 정렬되어 있기 때문에 아무런 의미가 없습니다.

나는 분명히 뭔가를 간과하고 있습니까, 아니면 iOS에서이 문제입니까?

답변

1

나는이 문제를 해결했다. 은 CoreText과 다르게 나타납니다. 이제 다음 코드를 사용하여 drawRect에 텍스트를 그립니다.

let totalRange = layoutManager.glyphRangeForTextContainer(textContainer) 

layoutManager.drawBackgroundForGlyphRange(range, atPoint: CGPointZero) 
layoutManager.drawGlyphsForGlyphRange(range, atPoint: CGPointZero)