如何在NSTextView中计算所选文本的正确坐标?

时间:2012-06-22 10:06:11

标签: cocoa calayer nstextview

我需要使用NSTextView使用CALayer覆盖在NSTextView中使用插入符号突出显示行,并在我的子类- (NSRect)overlayRectForRange:(NSRange)aRange { NSScreen *currentScreen = [NSScreen currentScreenForMouseLocation]; NSRect rect = [self firstRectForCharacterRange:aRange]; rect = [self convertRectToLayer:rect]; rect.origin = [currentScreen flipPoint:rect.origin]; rect = [self.window convertRectToScreen:rect]; return rect; } 中使用此代码获取rect行...:

- (void)focusOnLine
{
    NSInteger caretLocation = [aTextView selectedRange].location;
    NSRange neededRange;

    (void)[layoutMgr lineFragmentRectForGlyphAtIndex:caretLocation effectiveRange:&neededRange];
    CALayer *aLayer = [CALayer layer];
    [aLayer setFrame:NSRectToCGRect([aTextView overlayRectForRange:neededRange])];
    [aLayer setBackgroundColor:[[NSColor redColor] coreGraphicsColorWithAlfa:0.5]];
    [[aTextView layer] addSublayer:aLayer];
}

...并将叠加:

{{1}}

因此,选择叠加层与所需线条的宽度一致,但绝对不匹配Y轴(X轴正常)。

我错过了什么?

1 个答案:

答案 0 :(得分:8)

好的,我完全重写了方法overlayRectForRange:,现在一切正常。有固定的代码:

- (NSRect)overlayRectForRange:(NSRange)aRange
{
    NSRange activeRange = [[self layoutManager] glyphRangeForCharacterRange:aRange actualCharacterRange:NULL];
    NSRect neededRect = [[self layoutManager] boundingRectForGlyphRange:activeRange inTextContainer:[self textContainer]];
    NSPoint containerOrigin = [self textContainerOrigin];
    neededRect.origin.x += containerOrigin.x;
    neededRect.origin.y += containerOrigin.y;

    neededRect = [self convertRectToLayer:neededRect];

    return neededRect;
}