关闭

连续帧图片显示动画(Java)

标签: java图片动画
1245人阅读 评论(0) 收藏 举报
分类:

原理很简单,用Gif图片的连续几帧图片,在JPanel中画出来,显示出动态图效果


package multi_media;

import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyDraw extends JPanel{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private int curPic;
	private int allPic;
	private int picHeight;
	private int picWidth;
	private List<Image> images;
	
	public MyDraw() {
		try{
			final URI dir = getClass().getResource(".").toURI();
			String [] files = new File(dir).list();
			images = new ArrayList<Image>();
			for(String file : files) {
				if(file.toLowerCase().endsWith(".gif")) {
					Image i = ImageIO.read(new File(new File(dir), file));
					images.add(i);
					
					if(picHeight == 0 || picWidth == 0) {
						picHeight = i.getHeight(this);
						picWidth = i.getWidth(this);
					}
				}
			}
			
			allPic = images.size();
			
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	

	@Override
	protected void paintComponent(Graphics g) {
		// TODO Auto-generated method stub
		super.paintComponent(g);
		if(images == null || images.size() == 0) {
			return ;
		}
		
		//System.out.println(allPic);
		
		g.drawImage(images.get(curPic), 0, 0, this);
		
		curPic++;
		if(curPic == allPic)
			curPic = 0;
	}

	public static void main(String[] args) {
		
		JFrame f = new JFrame();
		MyDraw d = new MyDraw();
		f.add(d);
		
		f.setSize(d.picWidth, d.picHeight);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setVisible(true);
		
		while(true) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			d.repaint();
		}
		
	}
	
	
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场