我目前正在使用以下代码来获取字形的逻辑 NSView 位置,该位置工作正常,但似乎有点慢,并且位置并不精确地位于字符字距调整点和基线上。很可能我需要做的就是一一迭代字形本身并自己构建矩形。

现在这段代码(功能),只是想看看它是否可以更有效或更正确地完成。

// lastRange is any valid, bounds checked character range in an NSTextView


NSLayoutManager *layoutManager = [self layoutManager];
NSRect paragraphRect = [layoutManager boundingRectForGlyphRange:lastRange inTextContainer:[self textContainer]];

// Draw a gradient around the range.
NSGradient * gradient = [self indicatorGradient];
CGContextRef myContext = [[NSGraphicsContext currentContext] graphicsPort];
CGContextSetBlendMode(myContext , kCGBlendModeMultiply);
[gradient drawInRect:paragraphRect angle:90];
有帮助吗?

解决方案

这是这样做的方法。但是,如果lastRange是您所描述的characterRange,则必须将其通过

lastRange = [layoutManager glyphRangeForCharacterRange:lastRange actualRange:NULL];

首先得到正确的结果。您还需要确保考虑文本布局的文本容器的来源,然后执行

NSPoint containerOrigin = [[container textView] textContainerOrigin];
paragraphRect = NSOffsetRect(paragraphRect,containerOrigin.x,containerOrigin.y);

在绘图之前。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top