BufferedImage.getRGB方法不一致 - Java AWT

时间:2012-03-30 03:46:13

标签: java graphics applet awt

我正在使用Applet编写一个小游戏。我希望能够检查屏幕上像素的颜色。但是,当我在游戏循环中使用.getRGB()在我的缓冲图像上(一个循环执行一遍又一遍)时,即使像素颜色从未真正改变,它也会给出不一致的值!

例如,如果我用绿色填充图像并且我在屏幕中间的像素上调用.getRGB(),有时它会给我0xFF00FF00(绿色)作为颜色,有时它给我0xFF000000(黑色) )即使颜色总是保持绿色!

任何帮助?

以下是相关代码,如果有帮助,我将其最小化只是为了关注问题:

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

public class t extends Applet implements Runnable {
    Graphics2D      bufferG;
    BufferedImage   bufferI;
    final int       WIDTH   = 500, HEIGHT = 500;
    public void init() {
        setSize(WIDTH, HEIGHT);
        bufferI = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        bufferG = bufferI.createGraphics();
        (new Thread(this)).start();
    }
    public void run() {
        while (true){
            if (bufferI.getRGB(WIDTH/2, HEIGHT/2)==0xFF000000) System.out.println("BLACK");
        }
    }
    public void paint(Graphics g) {
        bufferG.setColor(Color.green);
        bufferG.fillRect(0, 0, WIDTH, HEIGHT);

        g.drawImage(bufferI, 0, 0, this);
    }
}

1 个答案:

答案 0 :(得分:1)

我不确定你为什么要处理缓冲区。这将图像描绘为绿色和在命令行上不生成输出(将颜色报告为黑色)。

// <applet code='t' width=400 height=200></applet>
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

public class t extends Applet implements Runnable {

    BufferedImage   bufferI;
    final int       WIDTH   = 500, HEIGHT = 500;
    public void init() {
        bufferI = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = bufferI.getGraphics();
        g.setColor(Color.GREEN);
        g.fillRect(0,0,WIDTH,HEIGHT);
        g.dispose();
        (new Thread(this)).start();
    }
    public void run() {
        while (true){
            if (bufferI.getRGB(WIDTH/2, HEIGHT/2)==0xFF000000) System.out.println("BLACK");
        }
    }
    public void paint(Graphics g) {
        g.drawImage(bufferI, 0, 0, this);
    }
}

备注

编译&amp;运行

prompt> javac t.java
prompt> appletviewer t.java  // yes that file extension is correct.

尺寸

applet的大小在加载它的HTML中设置,它不应该尝试设置自己的大小。