我编写了一个小应用程序,允许用户绘制多个形状,然后删除它们或调整它们的大小。它在矩形和椭圆形上完美运行,但我在处理线条时遇到了问题。
这是我编写的一个方法,用于查找屏幕上的点击点是否是特定行的一部分:
public boolean containsLocation(int x, int y) {
int m = (getY2() - getY()) / (getX2() - getX());
int b = getY() - (m * getX());
if (y == (m * x) + b) {
return true;
}
return false;
我使用著名的 y = mx + b 公式并替换 y 和 x,这是点击的坐标, 以查找单击的点是否是该行的一部分。
使用getter getX(), getY() 和getX2(), getY2() 确定原始坐标
问题是当我在屏幕上单击以删除线时,只有在该线开始的第一个坐标 (x,y) 上单击时它才有效。
当我点击这条线上的其他任何地方时,没有任何反应。
由于数学不是最强项,任何人都可以指出我做错了什么吗?
这是我的 Line 完整类(class):
public class Line extends Shape{
private int x2, y2;
public Line (int x, int y, int x2, int y2, Color lineColor) {
super(x, y, lineColor);
this.x2 = x2;
this.y2 = y2;
}
public void draw(Graphics g) {
g.setColor(getLineColor());
g.drawLine(getX(), getY(), getX2(), getY2());
}
@Override
public boolean containsLocation(int x, int y) {
int m = (getY2() - getY()) / (getX2() - getX());
int b = getY() - (m * getX());
if (y == (m * x) + b) {
return true;
}
return false;
}
public int getX2() {
return x2;
}
public void setX2(int x2) {
this.x2 = x2;
}
public int getY2() {
return y2;
}
public void setY2(int y2) {
this.y2 = y2;
}
这是由 Line 扩展的 Shape 类:
public abstract class Shape {
private int x, y;
private Color lineColor;
public Shape(int x, int y, Color lineColor) {
this.x = x;
this.y = y;
this.lineColor = lineColor;
}
public abstract void draw(Graphics g);
public abstract boolean containsLocation(int x, int y);
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Color getLineColor() {
return lineColor;
}
public void setLineColor(Color lineColor) {
this.lineColor = lineColor;
}
}
这是调用 containsLocation 的方法:
public Shape shapeFinder(int x, int y){
for (int i = shapes.size()-1; i >=0; i--){
if (shapes.get(i).containsLocation(x, y)){
return shapes.get(i);
}
}
return null;
}
这是应该删除线的方法(它适用于椭圆和矩形):
public void mousePressed(MouseEvent e) {
if (model.getAction() == Model.REMOVE) {
startX = e.getX();
startY = e.getY();
shape = model.shapeFinder(startX, startY);
if (shape != null) {
model.getShape().remove(model.shapeFinder(startX, startY));
}
最佳答案
您正在使用整数除法来计算斜率。我使用 (100,100) 到 (120, 153) 的示例,它给了我 2 的斜率。它应该是 2.65 的斜率。
但无论如何,您永远不会在我的直线中间找到任何整数点 - 我的直线上没有 x 和 y 都是整数的点。如果您正确计算斜率,您将能够识别端点,但您需要找到一种不同的方法来计算中间点。也许在您的方法中引入某种 epsilon?
关于java - 判断坐标是否在线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19730302/