1

I am trying to get the index of the closest character to a point.

The code below works perfectly fine as ling as my text alignment is set to left, as soon as I chage it to right or center it gives me the wrong index. What would be the solution to consider the text alignment while getting closest index to a point?

CTLineRef line = (CTLineRef)[lines objectAtIndex:i];
index = CTLineGetStringIndexForPosition(line, point);  

EDIT:

My text alignment is done by adding a paragraph style that has it's textAlignment setting to kCTCenterTextAlignment

aryaxt
  • 76,198
  • 92
  • 293
  • 442
  • hey aryaxt, how did you implement the solution given below? I assume it was something like "CTLineGetStringIndexForPosition(line, CGPointMake(origins[i].x + point.x, point.y));", but that doesn't work for me. Did you do it differently? – Ser Pounce Mar 26 '12 at 04:02

1 Answers1

4

The point is relative to the line's origin (which changes with the alignment), so you have to use CTFrameGetLineOrigins and add the x value of the line's origin to your point's x value.

omz
  • 53,243
  • 5
  • 129
  • 141
  • great answer as always, thanks. I was just curious how do u have so much knowledge about core text? Is there a specific project related to core text you've been working on? – aryaxt Jul 26 '11 at 04:00
  • I think the point is an absolute position, so we should subtract the x value of the line's origin from the point's x value? At least in my case it was subtraction. – giftederic Jul 24 '12 at 20:43