1

下面是来自 Romain Guy 和 Chet Haase 的“肮脏的富客户”的代码

private class ImageViewer extends JComponent {
    private BufferedImage image, landscape;

    private ImageViewer() {
        try {
            image = ImageIO.read(new File("picture.png"));
            landscape = ImageIO.read(new File("landscape.jpg"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        BufferedImage temp = new BufferedImage(getWidth(), getHeight(),
            BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = temp.createGraphics();

        if (shadow.isSelected()) {
            int x = (getWidth() - image.getWidth()) / 2;
            int y = (getHeight() - image.getHeight()) / 2;
            g2.drawImage(image, x + 4, y + 10, null);

            Composite oldComposite = g2.getComposite();
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, 0.75f));
            g2.setColor(Color.BLACK);
            g2.fillRect(0, 0, getWidth(), getHeight());
            g2.setComposite(oldComposite);
            g2.drawImage(image, x, y, null);
        } else {
            int x = (getWidth() - image.getWidth()) / 2;
            int y = (getHeight() - image.getHeight()) / 2;
            g2.drawImage(image, x, y, null);

            Composite oldComposite = g2.getComposite();
            g2.setComposite(AlphaComposite.SrcIn);
            x = (getWidth() - landscape.getWidth()) / 2;
            y = (getHeight() - landscape.getHeight()) / 2;
            g2.drawImage(landscape, x, y, null);
            g2.setComposite(oldComposite);
        }

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

选中复选框时,获取以下具有不同状态的输出是代码的一部分:- 在此处输入图像描述

我不明白的是

1)什么是线

BufferedImage temp = new BufferedImage(getWidth(), getHeight(),
        BufferedImage.TYPE_INT_ARGB);

在那里这样做是因为如果我只编写以下代码并运行,则输出中不会获得任何内容。

BufferedImage temp = new BufferedImage(getWidth(), getHeight(),
        BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = temp.createGraphics();

    if (jcb.isSelected()) {
        int x = (getWidth() - image.getWidth()) / 2;
        int y = (getHeight() - image.getHeight()) / 2;
        g2.drawImage(image, x + 4, y + 10, null);
           }

2)创建“temp”缓冲图像后需要获取g2吗?我不能像这样直接做吗

Graphics2D g2=(Graphics2D)g.create();

3) TYPE_INT_RGB 和 TYPE_INT_ARGB 的实际区别是什么?

4

1 回答 1

3

这是双缓冲: http ://docs.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html

您首先在屏幕外图像上绘制,在这种情况下,它由变量 temp 中引用的 BufferedImage 对象支持;然后你对屏幕外的图像做任何事情;最后,您通过 g.drawImage(temp, ...) 在组件上打印结果。这不是为了让用户看到由于直接在屏幕上构建的图像而导致的故障或伪影。

于 2012-10-28T11:58:43.570 回答