1. 程式人生 > >連續幀圖片顯示動畫(Java)

連續幀圖片顯示動畫(Java)

原理很簡單,用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();
		}
		
	}
	
	
}