import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.CubicCurve2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
import java.awt.geom.QuadCurve2D;
import java.util.Arrays;
import java.util.ArrayList;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class PathIteratorExtractor extends JComponent{
private Dimension preferredSize = new Dimension(200,200);
ArrayList<Shape> shapes = new ArrayList<Shape>();
public static void main(String[] args){
JFrame frame = new JFrame("Path Iterator In Action");
frame.getContentPane().add(new PathIteratorExtractor());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public PathIteratorExtractor(){
Shape s = new Ellipse2D.Double(5, 5, 100, 100);
PathIterator pi = s.getPathIterator(null);
shapes.clear();
double[] coords = new double[6];
int result = -1;
double[] nextOrigin = new double[2];
double[] lastMoveTo = new double[2];
while(!pi.isDone()){
result = pi.currentSegment(coords);
switch(result){
case PathIterator.SEG_MOVETO:
System.out.println("MoveTo " + Arrays.toString(new double[]{coords[0], coords[1]}));
nextOrigin[0] = coords[0];
nextOrigin[1] = coords[1];
lastMoveTo[0] = coords[0];
lastMoveTo[1] = coords[1];
break;
case PathIterator.SEG_CLOSE:
System.out.println("Line back to " + Arrays.toString(new double[]{lastMoveTo[0], lastMoveTo[1]}));
shapes.add(new Line2D.Double(nextOrigin[0], nextOrigin[1], lastMoveTo[0], lastMoveTo[1]));
nextOrigin[0] = lastMoveTo[0];
nextOrigin[1] = lastMoveTo[1];
break;
case PathIterator.SEG_LINETO:
System.out.println("LineTo " + Arrays.toString(new double[]{coords[0], coords[1]}));
shapes.add(new Line2D.Double(nextOrigin[0], nextOrigin[1], coords[0], coords[1]));
nextOrigin[0] = coords[0];
nextOrigin[1] = coords[1];
break;
case PathIterator.SEG_QUADTO:
System.out.println("QuadTo " + Arrays.toString(new double[]{coords[0], coords[1], coords[2], coords[3]}));
shapes.add(new QuadCurve2D.Double(nextOrigin[0], nextOrigin[1], coords[0], coords[1], coords[2], coords[3]));
nextOrigin[0] = coords[2];
nextOrigin[1] = coords[3];
break;
case PathIterator.SEG_CUBICTO:
System.out.println("CubicTo " + Arrays.toString(new double[]{coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]}));
shapes.add(new CubicCurve2D.Double(nextOrigin[0], nextOrigin[1], coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]));
nextOrigin[0] = coords[4];
nextOrigin[1] = coords[5];
break;
}
pi.next();
}
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
Color[] colors = new Color[]{Color.RED, Color.GREEN, Color.ORANGE, Color.BLUE, Color.WHITE, Color.BLACK};
for(int i = 0; i < shapes.size(); i++){
g2.setPaint(colors[i]);
g2.draw(shapes.get(i));
}
}
public Dimension getPreferredSize(){
return preferredSize;
}
}