亲宝软件园·资讯

展开

java动态图片 java实现动态图片效果

点丶错了。。 人气:0
想了解java实现动态图片效果的相关内容吗,点丶错了。。在本文为您仔细讲解java动态图片的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java,动态图片,下面大家一起来学习吧。

源码

package forGame;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

//动态效果
public class Demo_1 extends JFrame{
 //背景
 private BufferedImage bufferedImage;
 //窗体大小
 private int width;
 private int height;
 //要绘制的动态照片数组
 private BufferedImage[] images = new BufferedImage[4];
 //要绘制动态图中的那张
 private BufferedImage image;

 //初始化
 {
  if(bufferedImage == null){
   try {
    bufferedImage = ImageIO.read(new File("src\\image\\背景.png"));
    for(int i = 1;i < images.length + 1;i ++)
     images[i - 1] = ImageIO.read(new File("src\\image\\大飞机爆炸" + i + ".png"));
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  width = bufferedImage.getWidth();
  height = bufferedImage.getHeight();
  image = images[0];
 }

 public Demo_1(){
  super("动态测试");
  //设置窗口
  setSize(width,height);
  setLocationRelativeTo(null);
  setResizable(false);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setVisible(true);
  //启动线程
  MyThread myThread = new MyThread();
  myThread.start();
 }

 //双缓冲绘制解决图片闪烁问题
 @Override
 public void paint(Graphics g) {
  Image image = this.createImage(width,height);
  Graphics gImage = image.getGraphics();
  gImage.setColor(gImage.getColor());
  gImage.fillRect(0,0,width,height);
  super.paint(gImage);

  //绘制背景
  gImage.drawImage(bufferedImage,0 ,0 ,null );
  //绘制动态图片
  gImage.drawImage(this.image,0 ,100 ,null );

  //最后绘制缓冲后的图片
  g.drawImage(image,0 ,0 , null);
 }

 private int num = 0;//images数组内图片索引
 //线程内部类
 private class MyThread extends Thread{
  @Override
  public void run() {
   while(true) {
    if(num <= 3) {
     image = images[num ++];
    }
    else
     num = 0;
    repaint();
    try {
     sleep(100);//每隔100毫秒重绘一次
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }
 }

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

效果图

加载全部内容

相关教程
猜你喜欢
用户评论