为什么缓冲图像的子图像偏离了一个像素?

时间:2019-06-19 02:34:53

标签: java graphics bufferedimage graphics2d swingx

Blue bar "gap" right at transition period shown here. 本质上,我使用一个计时器绘制1和0的每一行,该计时器工作良好,直到到达帧的末尾为止,此时我将所有先前的绘图向上移动一行,然后绘制下一行行,因此看起来像向下滚动。我通过在两个BufferImage之间进行subImaging来做到这一点。但是,恰好在过渡期间,从我要复制的图像的背景上绘制了一个大约像素宽度的蓝色条,好像它没有绘制新数据的第一行。之后,它会表现出我想要的样子。

从调试到达到这一点,我的代码都很难看。以前,它只是在制作垂直线时画出同一行。

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(oldim, 0, 0, this);
}

public void addCell() {
    int size = 1;
    int shiftd = rac.getGen() - oldim.getHeight() > 0 ? rac.getGen() - panheight : 0;
    int shiftl = rac.getNumCells() - panwidth > 0 ? rac.getNumCells() - panwidth : 0;
    if (rac.getGen() - oldim.getHeight() >  0) {
        Graphics2D g2 = newim.createGraphics();
        g2.drawImage(oldim.getSubimage(0, 1, oldim.getWidth(), oldim.getHeight()-1),0, 0, Color.BLUE,null);
        g2.dispose();
        g2 = oldim.createGraphics();
        g2.drawImage(newim,0,0,this);
        for (int i = 0; i < rac.getNumCells(); i++) {
            if (rac.getCells()[i] == 1) {
                g2.setColor(Color.BLACK);
            } else {
                g2.setColor(Color.WHITE);
            }
            g2.fillRect(i * size - shiftl, oldim.getHeight()-1, size, size);
        }
        g2.dispose();
        BufferedImage temp = newim;
        newim = oldim;
        oldim = temp;
    }
    else {
        Graphics g = oldim.createGraphics();
        for (int i = 0; i < rac.getNumCells(); i++) {
            if (rac.getCells()[i] == 1) {
                g.setColor(Color.BLACK);
            } else {
                g.setColor(Color.WHITE);
            }
            g.fillRect(i * size - shiftl, rac.getGen() * size - shiftd, size, size);

        }
        g.dispose();
    }
    repaint();
}

0 个答案:

没有答案