3

Say, I have a sprite of a game object which is a png image with transparency.

Spaceship sprite

I want to create a polygon from this image which will contain my game object.

Spaceship polygon

I am pretty sure there is an existing algorithm for it, but I haven't found any.

I expect something like:

public static Polygon getPolygon(BufferedImage sprite)
{
    // get coordinates of all points for polygon
    return polygon;
}
Edward Ruchevits
  • 6,411
  • 12
  • 51
  • 86
  • It depends on how accurate you want it to be. For 100% accuracy, it would be very costly and could fill over 1000 points. That could be done through flood-fill or a series where it moves along the border through color analysis. –  Mar 11 '13 at 15:45
  • @Legend Thank you! I need some golden mean between accuracy and efficiency. I will read about the flood-fill algorithm. – Edward Ruchevits Mar 11 '13 at 15:52

1 Answers1

1

See this question. It will be slow, but it depends on how accurate you want it (second answer is sloppier, but a bit faster). After you get the Area from getOutline() on the other question, try using this code (untested):

public static Polygon getPolygonOutline(BufferedImage image) {
    Area a  = getOutline(image, new Color(0, 0, 0, 0), false, 10); // 10 or whatever color tolerance you want
    Polygon p = new Polygon();
    FlatteningPathIterator fpi = new FlatteningPathIterator(a.getPathIterator(null), 0.1); // 0.1 or how sloppy you want it
    double[] pts = new double[6];
    while (!fpi.isDone()) {
        switch (fpi.currentSegment(pts)) {
        case FlatteningPathIterator.SEG_MOVETO:
        case FlatteningPathIterator.SEG_LINETO:
            p.addPoint((int) pts[0], (int) pts[1]);
            break;
        }
        fpi.next();
    }
    return p;
}
Community
  • 1
  • 1