Java淡入淡出图像

时间:2013-12-03 08:56:45

标签: java image swing animation transparency

我正在尝试学习如何将图像淡入或淡出到另一张图像或另一张图像中。因此,如果我有2张图像,此时显示1,我想在背景中显示另一张图像,并将第一张图像淡入第二张图像。或者,我想将焦点设置在新图像上并在第一张图像上慢慢淡入,然后停止显示第一张图像。

我不确定如何:

    如果需要,
  1. 设置焦点。

  2. 如果我将alpha更改为0并增加并仅绘制一个图像,我可以淡入,但是我无法通过此代码的任何变化使其淡出。 (即评论出一幅图像)。

  3. 编辑:真的,我担心的是能够拥有2张图像并使当前正在显示的图像慢慢消失在第二张图像中。如何实现这一点并不需要与此相关。

    这是我正在搞乱的代码示例:

    import java.awt.AlphaComposite;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    
    public class FadeIn extends JPanel implements ActionListener {
    
        private Image imagem;
        private Image image2;
        private Timer timer;
        private float alpha = 1f;
    
        public FadeIn() {
            imagem = (new ImageIcon(getClass().getResource(
                 "/resources/1stImage.jpg"))).getImage();
            image2 = (new ImageIcon(getClass().getResource(
                 "/resources/2ndImage.jpg"))).getImage();    
            timer = new Timer(20, this);
            timer.start();
        }
        // here you define alpha 0f to 1f
    
        public FadeIn(float alpha) {
            imagem = (new ImageIcon(getClass().getResource(
                 "/resources/1stImage.jpg"))).getImage();
            this.alpha = alpha;
        }
    
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.drawImage(imagem, 0, 0, 400, 300, null);
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                    alpha));
            g2d.drawImage(image2, 0, 0, 400, 300, null);
        }
    
        public static void main(String[] args) {
            JFrame frame = new JFrame("Fade out");
            frame.add(new FadeIn());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(420, 330);
            // frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            alpha += -0.01f;
            if (alpha <= 0) {
                alpha = 0;
                timer.stop();
            }
            repaint();
        }
    }
    

2 个答案:

答案 0 :(得分:9)

基本上,这样做是使用相同的alpha值,从0-1逐渐消失,然后使用相同的alpha,从1-0开始,允许两个图像交叉淡入淡出...

Fading

魔术基本上发生在paintComponent,其中使用alpha值传入的图像和传出图像使用1f - alpha

在两张图片之间切换实际上是一个相同的过程,期望inImage交换outImage

时机略有不同。这不是使用标准增量(例如0-1)从0.01直接移动,而是使用基于时间的算法。

也就是说,我使用一个每40毫秒左右滴答一次的计时器,然后根据计时器运行的时间进行计算并相应地计算alpha值......

这允许您更改动画所需的时间,但也提供了一个稍微好一点的算法,该算法考虑了Swings渲染引擎的被动特性......

import java.awt.AlphaComposite;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class FadeImage {

    public static void main(String[] args) {
        new FadeImage();
    }

    public FadeImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class TestPane extends JPanel {

        public static final long RUNNING_TIME = 2000;

        private BufferedImage inImage;
        private BufferedImage outImage;

        private float alpha = 0f;
        private long startTime = -1;

        public TestPane() {
            try {
                inImage = ImageIO.read(new File("/path/to/inImage"));
                outImage = ImageIO.read(new File("/path/to/outImage"));
            } catch (IOException exp) {
                exp.printStackTrace();
            }

            final Timer timer = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (startTime < 0) {
                        startTime = System.currentTimeMillis();
                    } else {

                        long time = System.currentTimeMillis();
                        long duration = time - startTime;
                        if (duration >= RUNNING_TIME) {
                            startTime = -1;
                            ((Timer) e.getSource()).stop();
                            alpha = 0f;
                        } else {
                            alpha = 1f - ((float) duration / (float) RUNNING_TIME);
                        }
                        repaint();
                    }
                }
            });
            addMouseListener(new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent e) {
                    alpha = 0f;
                    BufferedImage tmp = inImage;
                    inImage = outImage;
                    outImage = tmp;
                    timer.start();
                }

            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(
                            Math.max(inImage.getWidth(), outImage.getWidth()), 
                            Math.max(inImage.getHeight(), outImage.getHeight()));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setComposite(AlphaComposite.SrcOver.derive(alpha));
            int x = (getWidth() - inImage.getWidth()) / 2;
            int y = (getHeight() - inImage.getHeight()) / 2;
            g2d.drawImage(inImage, x, y, this);

            g2d.setComposite(AlphaComposite.SrcOver.derive(1f - alpha));
            x = (getWidth() - outImage.getWidth()) / 2;
            y = (getHeight() - outImage.getHeight()) / 2;
            g2d.drawImage(outImage, x, y, this);
            g2d.dispose();
        }

    }

}

答案 1 :(得分:0)

对于大多数使用Java代码进行图像淡入淡出的开发人员来说,这是一个简单快捷的方法。

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 *
 * @author ADMIN
 */
public class ImageFade extends JFrame {

    ImageFade() {
        setLayout(null);

        JLabel l = new JLabel();
        l.setBounds(0, 0, 100, 96);
        add(l);

        Thread tp = new Thread() {
            @Override
            public void run() {
                for (int amp = 0; amp <= 500; amp++) {
                    try {
                        sleep(1);
                        try {
                            BufferedImage bim = ImageIO.read(new File("src/image/fade/image.png"));
                            BufferedImage nbim = new BufferedImage(bim.getWidth(), bim.getHeight(), BufferedImage.TYPE_INT_ARGB);
                            Graphics2D createGraphics = nbim.createGraphics();
                            createGraphics.drawImage(bim, null, 0, 0);
                            RescaleOp r = new RescaleOp(new float[]{1f, 1f, 1f, (float) amp / 500}, new float[]{0, 0, 0, 0}, null);
                            BufferedImage filter = r.filter(nbim, null);
                            l.setIcon(new ImageIcon(filter));
                        } catch (Exception ex) {
                            System.err.println(ex);
                        }
                    } catch (InterruptedException ex) {
                    }
                }
            }
        };
        tp.start();

        setUndecorated(true);
        setBackground(new Color(0, 0, 0, 0));
        setSize(100, 96);
        setVisible(true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        setAlwaysOnTop(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        ImageFade fr = new ImageFade();
    }
}

在此代码中,您可以看到线程代码。在线程中此图像将淡入。

使用的图像是堆栈溢出网页的徽标图像。

只有通过显示的代码,图像才会淡入。

Thread tp = new Thread() {
    @Override
    public void run() {
        for (int amp = 0; amp <= 500; amp++) {
            try {
                sleep(1);
                try {
                    BufferedImage bim = ImageIO.read(new File("src/image/fade/image.png"));
                    BufferedImage nbim = new BufferedImage(bim.getWidth(), bim.getHeight(), BufferedImage.TYPE_INT_ARGB);
                    Graphics2D createGraphics = nbim.createGraphics();
                    createGraphics.drawImage(bim, null, 0, 0);
                    RescaleOp r = new RescaleOp(new float[]{1f, 1f, 1f, (float) amp / 500}, new float[]{0, 0, 0, 0}, null);
                    BufferedImage filter = r.filter(nbim, null);
                    l.setIcon(new ImageIcon(filter));
                } catch (Exception ex) {
                      System.err.println(ex);
                  }
            } catch (InterruptedException ex) {
            }
        }
    }
};
tp.start();

此代码非常易于使用。

这不是来自任何书本,互联网等,而是我开发的。

正常图像无法更改Alpha。通过代码BufferedImage nbim = new BufferedImage(bim.getWidth(), bim.getHeight(), BufferedImage.TYPE_INT_ARGB);,图像将转换为ARGB-Alpha,Red,Green,Blue(R,G,B,A)图像。

因此您可以更改图像的Alpha。