根据像素偏移量获取字符串索引 [英] Getting a string index based on a pixel offset

查看:128
本文介绍了根据像素偏移量获取字符串索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我自定义绘制一个文本框,现在我正在实现用户可以点击一行并将光标移动到他点击的位置的部分。

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.

所以我有点从我'绘制字符串( 0 )然后我有点用户点击。如何获取他们点击的字符的字符串索引?

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?

额外信息:我正在通过将行存储在然后列出迭代列表,并在每行上使用 Graphics.DrawString

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.

推荐答案

没有简单的方法来查找像素处的字符。

There is no simple method to find the character at a pixel.

然而,您可以找到字符串将填充的像素。使用 Graphics.MeasureCharacterRanges 方法。您可以对字符串执行二分搜索,直到找到MeasureCharacterRanges返回您的光标位置的字符串。

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.

注意:您可能会看到 Graphics.MeasureString 方法并试图使用它。别!该方法不会返回准确的测量结果。我不记得为什么,但如果你尝试,你会做你的头!

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!

这篇关于根据像素偏移量获取字符串索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆