使图像淡入淡出? [英] Making an image fade in and fade out?
本文介绍了使图像淡入淡出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何让图像淡入淡出?我知道一个简单的方法来完成这个工作就是制作几张不同的不透明图像。
解决方案使用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;
定时器计时器;
私人浮动alpha = 0f;
public FadeIn(){
imagem = new ImageIcon(???。jpg)。getImage();
timer = new Timer(100,this);
timer.start();
}
//在这里你定义了alpha 0f到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);
$ b 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();
}
}
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.
解决方案
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();
}
}
这篇关于使图像淡入淡出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文