Find a character in a custom hand-drawn string at a given point

So, I am creating a custom control in C # (not WPF), and I basically want to implement text highlighting with the mouse.

How to effectively find a character in a given Point(say, where to click the mouse) in a string? I have a line layout rectangle when it was drawn, and I could calculate the line length to each character until I find the closest to where the mouse was clicked ... but there should be a better way. Any suggestions?

+3
source share
2 answers

, .
, string , , (, Text TextBox).
TextRenderer.MeasureText() (http://msdn.microsoft.com/en-us/library/7sy6awsb.aspx), , X , , .

, , Hello, .
X l o, 20.
MeasureText() :

  • H: 5 .
  • He: 10 .
  • Hel: 14 .
  • Hell: 17 .
  • Hello: 22 .

, l o, Hell.

=)

UPDATE:
, - . , , , , , , .
, , , . , O(n log n).
, O(1), =)

+3

, , BeemerGuy , - . ( ), . MeasureFont . , . , , .

+2

Source: https://habr.com/ru/post/1776506/


All Articles