3

好吧,经过整个下午的战斗,我似乎无法得到正确的答案。基本上,我有一个非常简单的设置,用白色背景填充我的画布 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)' 太长而无法发布,但基本上它所做的所有事情都需要参数值并编译一个点列表。

在此先感谢,靴子

4

2 回答 2

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);
于 2012-04-11T15:28:06.263 回答
0

当您创建/填充画布时,您正在使用一个BufferedImage对象。poligon 被捕获在一个Polygon对象中。对屏幕的实际渲染是通过操纵一个Graphics对象完成的——所以从某种意义上说,多边形是“浮动的”;即:它不会出现在画布上,而是在渲染 Graphics 对象时绘制在画布上。

您将需要在画布本身上实际渲染多边形,或从 Graphics 对象获取像素并对其执行计算

于 2012-04-11T15:32:54.430 回答