使用Java的2D绘图画布(JPanel)如何缩放绘图?

时间:2016-03-19 13:35:18

标签: java swing canvas

我尝试使用Java编写自己的引擎进行绘制。

当我使用绘图画布JFrame调整JPanel时,我遇到了问题。

代码:

public class DrawingCanvas extends JPanel{

    private BufferedImage image;

        @Override
        public void paintComponent(Graphics g) {
          super.paintComponent(g);


        image = new BufferedImage(this.getWidth(), this.getHeight(),  BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2 = (Graphics2D) image.getGraphics();
        clear(g2); // fill background white

        int wSize = actx.getMap().getW(); //ORIGINAL IMAGE SIZE Width
        int hSize = actx.getMap().getH(); //ORIGINAL IMAGE SIZE Height

        //calculate ascpect ration
        double wVypocet = (double) this.getWidth() / (double) wSize;
        double hVypocet = (double) this.getHeight() / (double) hSize;

        double min = Math.min(wVypocet, hVypocet);

        g2.scale(wVypocet, hVypocet);

        for (int i = 0; i < actx.getMap().gameMap.length; i++) {
            for (int j = 0; j < actx.getMap().gameMap[0].length; j++) {
                g2.setColor(actx.getMap().gameMapColorMap[i][j]); //set up my color
                g2.drawRect(i, j, 1, 1); //fill 1 pixel
            }
        }

            g2.dispose();
        g.drawImage(image, 0, 0, null);
   }

}

当我更改JFrame的大小时,我得到一个好的渲染或渲染失败:

GOOD RENDER: good render image enter image description here

RENDER FAIL:(图片干扰)fail render image enter image description here

为什么?

有没有更好的方法来实现调整大小?

感谢您的帮助。

0 个答案:

没有答案