Browniez Browniez - 2 months ago 26
Java Question

Java - Polygon not drawing on output image

I am attempting to draw a custom polygon onto an image I have called in using imageIO. once the polygon has been added, the image should then be output.

Below is my code:

public static void setPoints(List<Integer> pointArrayX, List<Integer> pointArrayY,File dest) throws IOException{

BufferedImage image = ImageIO.read(new File(dest+""));
Graphics2D g2d = image.createGraphics();


g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
g2d.setColor(Color.RED);
BasicStroke bs = new BasicStroke(2);
g2d.setStroke(bs);

int[] xPoly = new int[pointArrayX.size()];
int[] yPoly = new int[pointArrayY.size()];

Polygon poly = new Polygon(xPoly,yPoly,xPoly.length);
poly.getBounds();
g2d.setPaint(Color.RED);
g2d.drawPolygon(poly);
g2d.fillPolygon(xPoly, yPoly, xPoly.length);
g2d.drawPolygon(xPoly, yPoly, xPoly.length);
g2d.setStroke(bs);
g2d.drawPolyline(xPoly, yPoly, xPoly.length);
g2d.drawOval(100, 100, 200, 200);

g2d.draw(poly);


File outputfile = new File(dest+"");
ImageIO.write(image, "png", outputfile);


Once run, the only shape which appears in the output image is the Oval which I have defined. it is just the Polygon which does not appear.

Answer

You don't populate your arrays.

int[] xPoly = new int[pointArrayX.size()]; //create an array and set its size
int[] yPoly = new int[pointArrayY.size()]; //create an array and set its size
Polygon poly = new Polygon(xPoly,yPoly,xPoly.length); //use the created array

You need to add data to xPoly and yPoly. Try:

int[] xPoly = new int[pointArrayX.size()]; //create an array and set its size
int[] yPoly = new int[pointArrayY.size()]; //create an array and set its size

//loop i added to copy the elements from your method arguments to the new arrays
for(int i = 0; i < xPoly.size(); i++) {
    xPoly[i] = pointArrayX.get(i);
    yPoly[i] = pointArrayY.get(i);
}

Polygon poly = new Polygon(xPoly,yPoly,xPoly.length); //use the created array
Comments