package demo; //用Paht2D构成一个封闭多边形,然后用path2d.contains(point)方法来确定是否包含point import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.geom.Path2D; import javax.swing.JFrame; import javax.swing.JPanel; public class PointTest extends JFrame{ int[] xPoints = { 71, 163, 163, 256}; int[] yPoints = { 89, 89, 254, 254}; // 创建多段线路径 Path2D path = new Path2D.Double(); Point point = new Point(50, 50); Point point2 = new Point(117, 131); public PointTest() { path.moveTo(xPoints[0], yPoints[0]); // 将当前路径移动到指定的坐标 (x, y)。这个方法将设置路径的起始点。 for (int i = 1; i < xPoints.length; i++) { path.lineTo(xPoints[i], yPoints[i]); } System.out.println(path.contains(point)); System.out.println(path.contains(point2)); } public static void main(String[] args) { PointTest frame = new PointTest(); Canvas panel = new Canvas(); panel.path2d = frame.path; panel.point = frame.point; panel.point2 = frame.point2; frame.setContentPane(panel); frame.pack(); frame.setDefaultCloseOperation(3); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class Canvas extends JPanel { Path2D path2d; Point point, point2; @Override public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.BLUE); g2d.draw(path2d); g2d.setColor(Color.RED); g2d.fillOval(point.x, point.y, 4, 4); g2d.fillOval(point2.x, point2.y, 4, 4); } @Override public Dimension getPreferredSize() { return new Dimension(300, 200); } } 为什么点不在线上也为true
时间: 2024-04-11 13:29:44 浏览: 165
点不在线上的原因是因为在创建多边形路径时,没有使用闭合路径(即起点和终点不相连)。要使点在线上也为true,需要将路径闭合,即将起点和终点进行连接。可以在代码中添加以下语句将路径闭合:
path.closePath();
在PointTest构造函数中的for循环结束后,添加以上代码即可。修改后的代码如下:
public PointTest() {
path.moveTo(xPoints[0], yPoints[0]);
for (int i = 1; i < xPoints.length; i++) {
path.lineTo(xPoints[i], yPoints[i]);
}
path.closePath(); // 添加此行代码
System.out.println(path.contains(point));
System.out.println(path.contains(point2));
}
这样修改后,点在线上也会返回true。
阅读全文