如何让图像淡入淡出然后出来?我知道实现这一目标的一个简单方法就是制作具有不同不透明度的多张图像。
答案 0 :(得分:4)
绘制图像时使用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();
}
}
答案 1 :(得分:0)
使用deltaTime处理alpha值。所以,在给定的时间内你可以淡入淡出。
要淡出,你可以从1和每个渲染调用中启动alphaValue,减去.1直到它达到0.对于淡入,从0开始,在每个渲染调用中将.1添加到alphaValue,直到达到1。