Java examples for 2D Graphics:Line
get Adjacent Line
//package com.java2s; import java.awt.Shape; import java.awt.geom.Line2D; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; public class Main { /**/*from w ww.j ava 2s .c o m*/ * @param iterator * @param shape * @return */ public static Line2D getAdjacentLine(PathIterator iterator, Shape shape) { Point2D point1 = null; Point2D point2 = null; float[] segment = new float[6]; for (; !iterator.isDone(); iterator.next()) { int type = iterator.currentSegment(segment); if (type != PathIterator.SEG_MOVETO && type != PathIterator.SEG_LINETO) { continue; } point1 = point2; point2 = new Point2D.Float(segment[0], segment[1]); if (point1 != null && !shape.contains(point1) && shape.contains(point2)) { Line2D line = new Line2D.Float(point1, point2); Point2D pointOnBoundary = getPointOnBoundary(line, shape); line.setLine(point1, pointOnBoundary); return line; } } return null; } /** * get intersection point * @param line * @param shape * @return */ public static Point2D getPointOnBoundary(Line2D line, Shape shape) { double leftX = line.getX1(); double leftY = line.getY1(); double rightX = line.getX2(); double rightY = line.getY2(); // double h = shape.getBounds2D().getHeight(); // double w = shape.getBounds2D().getWidth(); // double lh = line.getBounds2D().getHeight(); // double lw = line.getBounds2D().getWidth(); // double lf = lh > lw ? lh : lw; // double f = h > w? h :w; // double factor = lf < f ? lf : f; // // if( factor == 0 ) factor = 2; double factor = 10; // shape contains line or shape do not intersect line if (shape.contains(leftX, leftY) == shape.contains(rightX, rightY)) { //throw new IllegalArgumentException(); return null; } if (shape.contains(leftX, leftY)) { double temp; // swap temp = leftX; leftX = rightX; rightX = temp; // swap temp = leftY; leftY = rightY; rightY = temp; } double tolerance = 1;//1.0; double centerX = leftX + (rightX - leftX) / factor; double centerY = leftY + (rightY - leftY) / factor; while (Math.abs(rightX - centerX) > tolerance || Math.abs(rightY - centerY) > tolerance) { if (shape.contains(centerX, centerY)) { rightX = centerX; rightY = centerY; } else { leftX = centerX; leftY = centerY; } centerX = leftX + (rightX - leftX) / factor; centerY = leftY + (rightY - leftY) / factor; } return new Point2D.Double(centerX, centerY); } }