我正在将多行字符串分解为iOS上的单词边界。我的解决方案围绕NSLayoutManager的boundingRectForGlyphRange方法。它的工作原理是正确的,只是每个单词的矩形在右侧偏离了几个像素。换句话说,NSLayoutManager似乎在每行上添加了前导空格/缩进,而我找不到任何方法来覆盖此行为。
我尝试使用NSLayoutManager.usesFontLeading以及NSParagraphStyle.headIndent,但没有任何结果:
NSLayoutManager* layout = [NSLayoutManager new];
layout.usesFontLeading = NO;
NSMutableParagraphStyle* paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.headIndent = paragraphStyle.firstLineHeadIndent = 0;
NSTextStorage* textStorage = [[NSTextStorage alloc] initWithString:self attributes:@{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle}];
layout.textStorage = textStorage;
NSTextContainer* textContainer = [[NSTextContainer alloc] initWithSize:size];
[layout addTextContainer:textContainer];
// compute bounding rect for each word range
for (NSValue* wordRangeValue in wordRanges)
{
NSRange wordRange = [wordRangeValue rangeValue];
NSRange wordGlyphRange = [layout glyphRangeForCharacterRange:wordRange actualCharacterRange:NULL];
CGRect wordBounds = [layout boundingRectForGlyphRange:wordGlyphRange inTextContainer:textContainer];
}
屏幕截图:灰色矩形代表标签范围,红色矩形代表每个标签的文本rect和上面[boundingRectForGlyphRange:]方法中计算的单词边界。请注意,计算出的单词边界偏离了几个像素。
我也对计算单词边界的其他方法持开放态度,但是boundingRectForGlyphRange对于我的目的来说似乎非常方便。
最佳答案
要忽略左边距,请使用:
textContainer.lineFragmentPadding = 0;
关于ios - 在NSLayoutManager中使用boundingRectForGlyphRange计算单词边界时,如何消除前导空白,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21666258/