检查Java Swing中的点是否在线 [英] Check if point is on line in Java Swing

查看:171
本文介绍了检查Java Swing中的点是否在线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我画了一条线然后是一个点,然后我想检查点是否在线上。我在数组中采用了一个线坐标(因为有多个线)。我想检查最后一行的当前点?

I have drawn a line and then a point, and then I want to check if the point is on the line or not. I have taken a line coordinate in array (as there was more than one line). I want to check the current point in on the last line or not?

if (positionX1 == positionX2 && positionY1 == positionY2) {
    float m = line.getSlope(
        drawLines[currentLines - 1][2], drawLines[currentLines - 1][3],
        drawLines[currentLines - 1][0], drawLines[currentLines - 1][1]);
    m = Float.parseFloat(df.format(m));
    float c = line.getIntercept(
        drawLines[currentLines - 1][2], drawLines[currentLines - 1][3],
        drawLines[currentLines - 1][0], drawLines[currentLines - 1][1]);
    c = Math.round(c);
    m1 = line.getSlope(positionX2, positionY2,
        drawLines[currentLines - 1][0], drawLines[currentLines - 1][1]);
    m1 = Float.parseFloat(df.format(m1));
    System.out.println(m + "   " + m1);
    c1 = line.getIntercept(positionX2, positionY2,
        drawLines[currentLines - 1][0], drawLines[currentLines - 1][1]);
    c1 = Math.round(c1);

    if (m == m1 && ((c == c1) || (c == c1 - 1) || (c == c1 + 1))) {
        System.out.println("Point is on Line");
    }
}

问题是当一个点接近起点时线或当一条线约为m1和c1的垂直值时,变化差别很大。因此,检测一个点是否在线存在问题。我如何检查这种情况?

Problem is when a point is near the starting point of line or when a line is about vertical values of m1 and c1 changes with big difference. So, there's a problem for detecting if a point on line or not. How can I check for this situation?

推荐答案

Line2D.ptSegDist(x1, y1,x2,y2,xP,yP) 如果点(xP,yP)位于从(x1,y1)到(x2,y2)的线段上,则返回0.0。 Line2D.ptLineDist 为无限行做同样的事情。

Line2D.ptSegDist(x1, y1, x2, y2, xP, yP) returns 0.0 if the point (xP, yP) is on the line segment from (x1, y1) to (x2, y2). Line2D.ptLineDist does the same thing for the infinite line.

这篇关于检查Java Swing中的点是否在线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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