好吧,经过整个下午的战斗,我似乎无法得到正确的答案。基本上,我有一个非常简单的设置,用白色背景填充我的画布 BufferedImage。然后我从我的 args 数组中的点绘制一个多边形。显示方面,这非常有效。当我想计算多边形(已填充)用完的像素数时,问题就出现了。
为此,我遍历画布并使用 getRGB 方法比较每个像素,如果它不是白色(背景颜色),我增加了一个计数器。但是,我总是得到的结果是画布的尺寸(640*480),这意味着整个画布都是白色的。
所以我假设被绘制到屏幕上的多边形没有添加到画布上,而是漂浮在顶部?这是我能想出的唯一答案,但可能是完全错误的。
我想要的是能够计算不是白色的像素数。有什么建议么?
代码:
public class Application extends JPanel {
public static int[] xCoord = null;
public static int[] yCoord = null;
private static int xRef = 250;
private static int yRef = 250;
private static int xOld = 0;
private static int yOld = 0;
private static BufferedImage canvas;
private static Polygon poly;
public Application(int width, int height) {
canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
fillCanvas(Color.WHITE);
poly = new Polygon(xCoord, yCoord, xCoord.length);
//Loop through each pixel
int count = 0;
for (int i = 0; i < canvas.getWidth(); i++)
for (int j = 0; j < canvas.getHeight(); j++) {
Color c = new Color(canvas.getRGB(i, j));
if (c.equals(Color.WHITE))
count++;
}
System.out.println(count);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(canvas, null, null);
g2.fillPolygon(poly);
}
public void fillCanvas(Color c) {
int color = c.getRGB();
for (int x = 0; x < canvas.getWidth(); x++) {
for (int y = 0; y < canvas.getHeight(); y++) {
canvas.setRGB(x, y, color);
}
}
repaint();
}
public static void main(String[] args) {
if (args != null)
findPoints(args);
JFrame window = new JFrame("Draw");
Application panel = new Application(640, 480);
window.add(panel);
Dimension SIZE = new Dimension(640, 480);
window.setPreferredSize(SIZE);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.pack();
}//end main
方法 'findPoints(args)' 太长而无法发布,但基本上它所做的所有事情都需要参数值并编译一个点列表。
在此先感谢,靴子