Making an image fade in and fade out? [closed]

假装没事ソ 提交于 2019-12-14 04:14:30

问题


How would I go about making an image fade in and then out? I know an easy way to accomplish this is to just make several images with different opacities.


回答1:


Use an AlphaComposite when painting the image:

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 {

    Image imagem;
    Timer timer;
    private float alpha = 0f;

    public FadeIn() {
        imagem = new ImageIcon("???.jpg").getImage();
        timer = new Timer(100, this);
        timer.start();
    }
// here you define alpha 0f to 1f
    public FadeIn(float alpha) {
        imagem = new ImageIcon("???.jpg").getImage();
        this.alpha = alpha;

    }
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;

        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                                                    alpha));
        g2d.drawImage(imagem, 0, 0, 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);
    }


    public void actionPerformed(ActionEvent e) {
        alpha += 0.05f;
        if (alpha >1) {
            alpha = 1;
            timer.stop();
        }
        repaint();
    }
}



回答2:


Manipulate alpha value using deltaTime. So, in a given period of time you can fade in and out.

To fade out, you can start alphaValue from 1 and in every render call, subtract .1 until it reaches 0. For fade in, start with 0 and in every render call add .1 to the alphaValue until it reaches 1.



来源:https://stackoverflow.com/questions/17731576/making-an-image-fade-in-and-fade-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!