好的,经过整个下午的争斗,我似乎无法得到正确的答案。 基本上,我有一个非常简单的设置,填充我的画布,BufferedImage,白色背景。然后我从来自args数组的点绘制一个Polygon。显示方式,这非常有效。当我想计算Polygon(已填充)的像素数时,问题就出现了。
为此,我在画布上循环并使用getRGB方法比较每个像素,如果它不是白色(背景颜色),我增加了一个计数器。但是,我总是得到的结果是画布的尺寸(640 * 480),这意味着整个画布是白色的。
所以我假设被绘制到屏幕的Polygon没有被添加到画布上,并且漂浮在顶部?这是我能想到的唯一答案,但可能是完全错误的。
我想要的是能够计算非白色像素的数量。有什么建议?
代码:
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)'太长而无法发布,但基本上所有它都需要参数值并编译一个点列表。
提前致谢, 靴
答案 0 :(得分:1)
只需添加感叹号即可反转条件中的布尔值:
if (!c.equals(Color.WHITE))
更快的方法是检查rgb值,而不是先创建它的Color对象:
if ((rgb & 0xFFFFFF) != 0xFFFFFF)
创建BufferedImage,绘制多边形并计数。基本上,这个:
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
Graphics2D g = img.createGraphics();
g.fill(polygon);
g.dispose();
countThePixels(img);
答案 1 :(得分:0)
创建/填充画布时,您正在使用BufferedImage
对象。 poligon在Polygon
对象中捕获。屏幕的实际渲染是在操纵Graphics
对象完成的 - 所以在某种意义上,多边形是“浮动的”;也就是说:它不会显示在画布上,而是在渲染Graphics对象时绘制在它上面。
您需要在画布上实际渲染多边形,或者从Graphics对象获取像素并对其执行计算