3

我需要在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;
}

...并放置叠加层:

- (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];
}

结果,选择覆盖与所需线的宽度一致,但绝对不匹配 Y 轴(X 轴可以)。

我错过了什么?

4

1 回答 1

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;
}
于 2012-06-22T11:33:11.610 回答