根据像素偏移获取字符串索引
我正在自定义绘制一个文本框,现在我正在实现用户可以单击一行并将光标移动到他单击的位置的部分。
我知道如何获取他单击的文本行,因为所有字体的字符高度都是恒定的,但不是列,因为我不确定如何说“获取在这个数量之前可以绘制的所有文本”像素”,并且因为除非您使用固定宽度字体,否则字符宽度不一致,这并不能保证。
所以我有绘制字符串的点 (0
),然后有用户单击的点。如何获取他们单击的字符的字符串索引?
额外信息:我通过将行存储在列表中然后迭代列表并在每行上使用 Graphics.DrawString
来绘制文本。
I am custom drawing a text box and now I am implementing the part where the user can click on a line and have the cursor move to where he clicked.
I know how to get the row of text he clicked on because the character height is constant across all fonts, but not the column, because I'm not sure how to say "get me all the text that can be drawn before this amount of pixels," and because character width is not consistent unless you're using a fixed-width font, which is not a guarantee.
So I have the point from which I'm drawing the string (0
) then I have the point that the user clicked. How do I get the string index of the character they clicked on?
Extra info: I am drawing the text by storing the lines in a List then iterating the list and using Graphics.DrawString
on each line.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有简单的方法可以找到像素处的字符。
但是您可以找到字符串将填充的像素。使用 Graphics.MeasureCharacterRanges 方法。您可以对字符串执行二分搜索,直到找到 MeasureCharacterRanges 返回光标位置的字符串。
注意:您可能会看到Graphics.MeasureString方法并想使用它。不!该方法不会返回准确的测量结果。我不记得为什么,但如果你尝试的话,你就会努力的!
There is no simple method to find the character at a pixel.
However you can find the pixels that a string will fill. Use the Graphics.MeasureCharacterRanges method. You can perform a binary search on your string until you find the string where MeasureCharacterRanges returns your cursor position.
Note: You might see the Graphics.MeasureString method and be tempted to use that. DON'T! That method doesn't return accurate measurements. I can't remember why, but you will do your head in if you try!