getPerimeterPoint(VertexView view, Point2D source, Point2D p)
是获取VertexView的边框与连线之间的交叉点的方法。
源码:
/** * Returns the intersection of the bounding rectangle and the straight line * between the source and the specified point p. The specified point is * expected not to intersect the bounds. */ public Point2D getPerimeterPoint(VertexView view, Point2D source, Point2D p) { Rectangle2D bounds = view.getBounds(); Icon icon = GraphConstants.getIcon(view.getAllAttributes()); double x = bounds.getX(); double y = bounds.getY(); double width = bounds.getWidth(); double height = bounds.getHeight(); double xCenter = x + width / 2; double yCenter = y + height / 2; double dx = p.getX() - xCenter; // Compute Angle double dy = p.getY() - yCenter; double alpha = Math.atan2(dy, dx); double xout = 0, yout = 0; double pi = Math.PI; double pi2 = Math.PI / 2.0; double beta = pi2 - alpha; double t = Math.atan2(height, width); if (alpha < -pi + t || alpha > pi - t) { // Left edge xout = x; yout = yCenter - width * Math.tan(alpha) / 2; } else if (alpha < -t) { // Top Edge yout = y; xout = xCenter - height * Math.tan(beta) / 2; } else if (alpha < t) { // Right Edge xout = x + width; yout = yCenter + width * Math.tan(alpha) / 2; } else { // Bottom Edge yout = y + height; xout = xCenter + height * Math.tan(beta) / 2; } return new Point2D.Double(xout, yout); }
如果想在连线连接图元对象时,连接到图元的图标范围上,而不是连接到图元的边框上(有些图元设置了小图标,而显示的名称很小,连线连到图元的边框时,看上去感觉不是连接到图元上)
连接到图标上,可以修改如下:
/** * Returns the intersection of the bounding rectangle and the straight line * between the source and the specified point p. The specified point is * expected not to intersect the bounds. */ public Point2D getPerimeterPoint(VertexView view, Point2D source, Point2D p) { Rectangle2D bounds = view.getBounds(); //获取图标 Icon icon = GraphConstants.getIcon(view.getAllAttributes()); if (icon != null) {//图标不为空 //获取X坐标偏移的大小 double doubX = bounds.getX() + (bounds.getWidth()-icon.getIconWidth())/2; //重新构建边框(图标的边框) bounds = new Rectangle2D.Double(doubX, bounds.getY(), icon.getIconWidth(), icon.getIconWidth()); } double x = bounds.getX(); double y = bounds.getY(); double width = bounds.getWidth(); double height = bounds.getHeight(); double xCenter = x + width / 2; double yCenter = y + height / 2; double dx = p.getX() - xCenter; // Compute Angle double dy = p.getY() - yCenter; double alpha = Math.atan2(dy, dx); double xout = 0, yout = 0; double pi = Math.PI; double pi2 = Math.PI / 2.0; double beta = pi2 - alpha; double t = Math.atan2(height, width); if (alpha < -pi + t || alpha > pi - t) { // Left edge xout = x; yout = yCenter - width * Math.tan(alpha) / 2; } else if (alpha < -t) { // Top Edge yout = y; xout = xCenter - height * Math.tan(beta) / 2; } else if (alpha < t) { // Right Edge xout = x + width; yout = yCenter + width * Math.tan(alpha) / 2; } else { // Bottom Edge yout = y + height; xout = xCenter + height * Math.tan(beta) / 2; } return new Point2D.Double(xout, yout); }