在NSLayoutManager中使用boundingRectForGlyphRange计算单词边界时,如何消除前导空白 [英] How do I eliminate leading whitespace when computing word boundaries using boundingRectForGlyphRange in NSLayoutManager

查看:509
本文介绍了在NSLayoutManager中使用boundingRectForGlyphRange计算单词边界时,如何消除前导空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将多行字符串分解为iOS上的单词边界.我的解决方案围绕NSLayoutManager的boundingRectForGlyphRange方法.它的工作原理是正确的,除了每个单词的rect在右边偏离几个像素之外.换句话说,NSLayoutManager似乎在每行上添加了前导空格/缩进,而我找不到任何方法来覆盖此行为.

I am decomposing a multiline string into word boundaries on iOS. My solution centers around the boundingRectForGlyphRange method of NSLayoutManager. It ALMOST works, except that the rect for each word is a few pixels off to the right. In other words NSLayoutManager seems to be adding a leading space / indent on each line and I cannot find any way to override this behavior.

我尝试使用NSLayoutManager.usesFontLeading以及NSParagraphStyle.headIndent,但没有任何结果:

I tried using NSLayoutManager.usesFontLeading as well as NSParagraphStyle.headIndent but without any results:

 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:]方法的计算出的单词边界.请注意,计算出的单词边界偏离了几个像素.

Screenshot: the gray rectangles represent label bounds, red rectangles represent text rect for each label and computed word boundaries from the [boundingRectForGlyphRange:] method above. Notice that the computed word boundaries are off by a few pixels.

我也欢迎使用其他方法来计算单词边界,但是boundingRectForGlyphRange对于我的目的来说似乎非常方便.

I am also open to other methods for computing word boundaries, but boundingRectForGlyphRange seems very convenient for my purpose.

推荐答案

要忽略左边距,请使用:

To ignore the left margin, use:

textContainer.lineFragmentPadding = 0;

这篇关于在NSLayoutManager中使用boundingRectForGlyphRange计算单词边界时,如何消除前导空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆