Java写的动画gif

来源:互联网 发布:中国4g网络协会 编辑:程序博客网 时间:2024/06/06 05:32
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;


public class Animation extends Applet implements Runnable{


Image igs[];//用于装载组成gif动画的jpg图片
MediaTracker mt;//声明了一个MediaTracker对象,是一个跟踪多种媒体对象状态的使用工具,目前仅支持图片
Image image;//声明一个图片对象;是一个抽象类,是表示图形图像的所有类的父类
int hight=200,width=200;//定义界面大小
Graphics gh;//声明一个画笔对象,是所有图像上下文的抽象基类,允许应用程序可以在组件以及图像进行绘制
boolean flag=false;
int id=0;
Thread th;//声明了一个线程对象

public void init()
{
igs=new Image[8];//对图像数组进行实例化
mt=new MediaTracker(this);
image=this.createImage(width, hight);//创建缓冲区,绘制屏幕图像
gh=image.getGraphics();
//gh.setColor(Color.white);
gh.fillRect(0, 0, width, hight);//指定要绘制的矩形的位置和大小
this.setSize(width,hight);
for(int i=0;i<igs.length;i++)
{
String file_name=(i+1)+".jpg";//获取图片名称
igs[i]=this.getImage(getCodeBase(),file_name);//获取图片
mt.addImage(image, i);//放到图片的追踪器里面
}
try {
mt.waitForAll();//加载跟踪器里面的所有图片
} catch (InterruptedException e) {
e.printStackTrace();
}
flag=true;//将标识改成true,标记着已经加载完成

}

public void paint(Graphics g)
{
if(flag){
g.drawImage(image,0,0,this);//画出该图像
}
}

public void start()
{
if(mt.checkID(id))
{
gh.drawImage(igs[id],0,0,this);//画出图片
}
th=new Thread(this);
th.start();
}

public void run()
{
while((th!=null))
{
if(mt.checkID(id))
{
gh.fillRect(0, 0, width, hight);
gh.drawImage(igs[id], 0, 0, this);
id++;
if(id>=igs.length)
{
//如果图片绘制完毕
id=0;
}
}
try {
th.sleep(100);//线程休眠0.1s
} catch (InterruptedException e) {
e.printStackTrace();
}
this.repaint();//重新绘制
}
}

public static void main(String[] args){
new Animation();
}

}












0 0