使图像淡入淡出?

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


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.

我怎样才能让图像淡入淡出然后出来?我知道一个简单的方法就是制作具有不同不透明度的几张图像。

2 个解决方案

#1


4  

Use an AlphaComposite when painting the image:

绘制图像时使用AlphaComposite:

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


0  

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

使用deltaTime操纵alpha值。所以,在给定的时间内你可以淡入淡出。

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.

要淡出,你可以从1和每个渲染调用中启动alphaValue,减去.1直到它达到0.对于淡入,从0开始,在每个渲染调用中将.1添加到alphaValue,直到达到1。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/07/18/e336f6e85854ea17e4689d984266a984.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com