简体   繁体   English

如何在NSTextView中找到字符的像素位置?

[英]How do I find the pixel position of a character in an NSTextView?

I'm currently using the following code to fetch the logical NSView position of glyphs which is working fine however it seems a bit slow and the positions aren't precisely on the character kerning point and baseline. 我目前正在使用以下代码来获取字形的逻辑NSView位置,这种位置工作正常但是它似乎有点慢并且位置不精确地在字符字距调整点和基线上。 It very well may be the case that all I need to do is iterate the glyphs themselves one by one and build the rect myself. 很可能我需要做的就是逐个迭代字形并自己构建矩形。

This code (functions) now, just want to see if it can be done more efficiently or properly. 现在这个代码(函数),只是想看看它是否可以更高效或更正确地完成。

// 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];

This is the way to do it. 这是做到这一点的方法。 However if lastRange is a characterRange as you described, you have to put it through 但是,如果lastRange是您描述的characterRange,则必须通过它

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

first to get correct results. 首先得到正确的结果。 you also need to make sure to account for the origin of the textcontainer the text is layouted in and then do a 您还需要确保考虑文本所在的文本容器的来源,然后执行

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

before drawing. 在绘图之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM