我试图在我使用imageIO调用的图像上绘制自定义多边形。添加多边形后,应输出图像。
以下是我的代码:
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);
一旦运行,输出图像中出现的唯一形状就是我定义的椭圆形。它只是没有出现的Polygon。
答案 0 :(得分:0)
您不会填充阵列。
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
您需要将数据添加到xPoly
和yPoly
。尝试:
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