簡體   English   中英

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

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

我目前正在使用以下代碼來獲取字形的邏輯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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM