2013-03-25 4 views
2

У меня есть canvas с lines. На click Я хочу проверить, был ли щелчок на моей строке, чтобы выделить его.Как проверить, находится ли точка на диагональной линии?

У меня также есть rectangles, где это просто, просто используя start и end point площади. Но для diagonal line Я не могу использовать ту же технику, что и линия не заполняет прямоугольник.

Но как я могу достичь этого? Кроме того, я хотел бы также иметь «смещение», чтобы, если щелчок был достаточно близок к строке, он также помечен, так как тонкие линии могут быть трудно щелкнуть иначе.

Возможно, мне не хватает правильных ключевых слов, так как я точно не первый, кто хочет это сделать. Надеюсь, ты сможешь помочь.

+1

Любой хороший? http://stackoverflow.com/a/9114951/2065121 –

+0

нет awt в gwt roger, но вы можете извлечь код. –

ответ

3

Gabor прав, это довольно легко вычислить расстояние между двумя точками и использовать это. Основываясь на предложенной Роджером ссылке, вот некоторый извлеченный код из исходного кода AWT, который измеряет расстояние между двумя точками. http://developer.classpath.org/doc/java/awt/geom/Line2D-source.html

так, вы код будет что-то вроде

if (ptLineDist(lineX1,lineY1,lineX2,lineY2,clickX,clickY) < someLimit) 
    clicked=true; 
else clicked=false; 

Вот код AWT (проверьте ссылку выше для лицензии)

521: /** 
522: * Measures the square of the shortest distance from the reference point 
523: * to a point on the infinite line extended from the segment. If the point 
524: * is on the segment, the result will be 0. If the segment is length 0, 
525: * the distance is to the common endpoint. 
526: * 
527: * @param x1 the first x coordinate of the segment 
528: * @param y1 the first y coordinate of the segment 
529: * @param x2 the second x coordinate of the segment 
530: * @param y2 the second y coordinate of the segment 
531: * @param px the x coordinate of the point 
532: * @param py the y coordinate of the point 
533: * @return the square of the distance from the point to the extended line 
534: * @see #ptLineDist(double, double, double, double, double, double) 
535: * @see #ptSegDistSq(double, double, double, double, double, double) 
536: */ 
537: public static double ptLineDistSq(double x1, double y1, double x2, double y2, 
538:          double px, double py) 
539: { 
540:  double pd2 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); 
541: 
542:  double x, y; 
543:  if (pd2 == 0) 
544:  { 
545:   // Points are coincident. 
546:   x = x1; 
547:   y = y2; 
548:  } 
549:  else 
550:  { 
551:   double u = ((px - x1) * (x2 - x1) + (py - y1) * (y2 - y1))/pd2; 
552:   x = x1 + u * (x2 - x1); 
553:   y = y1 + u * (y2 - y1); 
554:  } 
555: 
556:  return (x - px) * (x - px) + (y - py) * (y - py); 
557: } 
558: 
559: /** 
560: * Measures the shortest distance from the reference point to a point on 
561: * the infinite line extended from the segment. If the point is on the 
562: * segment, the result will be 0. If the segment is length 0, the distance 
563: * is to the common endpoint. 
564: * 
565: * @param x1 the first x coordinate of the segment 
566: * @param y1 the first y coordinate of the segment 
567: * @param x2 the second x coordinate of the segment 
568: * @param y2 the second y coordinate of the segment 
569: * @param px the x coordinate of the point 
570: * @param py the y coordinate of the point 
571: * @return the distance from the point to the extended line 
572: * @see #ptLineDistSq(double, double, double, double, double, double) 
573: * @see #ptSegDist(double, double, double, double, double, double) 
574: */ 
575: public static double ptLineDist(double x1, double y1, 
576:         double x2, double y2, 
577:         double px, double py) 
578: { 
579:  return Math.sqrt(ptLineDistSq(x1, y1, x2, y2, px, py)); 
580: } 
581: 
+0

+1, спасибо за копание кода, я был слишком ленив, чтобы написать все уравнения с координатами линий. Фактически вы можете выразить 'a' и' b' с отличиями x и y координат 1 конечной точки, как показано в примере кода. – gaborsch

4

Написать уравнение для линии:

a*x + b*y + c = 0 

Затем поместите ваши кликали координаты в это уравнение:

distance = a*x1 + b*y1 + c 

где (x1, y1) является точкой вы нажали. Если distance < threshold вы нажали на строку.

+0

У меня есть линия, которая заканчивается на обоих концах, а не бесконечна. Разве это не дало бы мне также положительный результат на кликах, где линия была бы мнимой? – membersound

Смежные вопросы