代碼主要為以下:
網(wǎng)站建設哪家好,找創(chuàng)新互聯(lián)建站!專注于網(wǎng)頁設計、網(wǎng)站建設、微信開發(fā)、微信小程序開發(fā)、集團企業(yè)網(wǎng)站建設等服務項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了保靖免費建站歡迎大家使用!
package com.lovo.game.frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import javax.swing.JFrame;
import com.lovo.game.role.Fire;
import com.lovo.game.role.GameMap;
import com.lovo.game.role.ZhaoYun;
import com.lovo.game.util.TrackerInit;
public class GameStartFrame extends JFrame implements Runnable{
private Image memoryImage;
private Graphics memoryGraphics;
public static boolean isRun = true;
private static GameMap gameMap = new GameMap();
private ZhaoYun zy = new ZhaoYun();
private Fire fire = new Fire();
public GameStartFrame(){
this.setSize(900,700);
this.setVisible(true);
this.setDefaultCloseOperation(3);
//設置居中
this.setLocationRelativeTo(null);
//初始化雙緩沖畫布、畫筆
this.memoryImage = this.createImage(900,700);
this.memoryGraphics = this.memoryImage.getGraphics();
//媒體追蹤器
MediaTracker tracker = new MediaTracker(this);
TrackerInit.initImage(tracker);
//啟動線程
Thread th = new Thread(this);
th.start();
}
public static void main(String[] args) {
GameStartFrame game = new GameStartFrame();
}
public void run() {
while(isRun){
this.flushFrame();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void flushFrame(){
gameMap.drawMap(memoryGraphics);
zy.drawImage(memoryGraphics);
fire.drawImage(memoryGraphics);
//將雙緩沖畫布中的圖片顯示在窗體
this.getGraphics().drawImage(this.memoryImage,0,0,this);
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package com.lovo.game.role;
import java.awt.Graphics;
import java.awt.Image;
public class GameMap {
public static Image mapImg;
public static int mapx;
public void drawMap(Graphics memoryGraphics){
mapx -=5;
if(mapx =-17100){
mapx = -17100;
}
memoryGraphics.drawImage(mapImg,mapx,0,null);
}
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package com.lovo.game.role;
import java.awt.Graphics;
import java.awt.Image;
import com.lovo.game.util.MoveImageChange;
public class Fire {
public static Image[]fireImage;
private int x =100;
private int y =300;
private int width = 200;
private int height = 130;
private MoveImageChange moveChange = new MoveImageChange(3);
public void drawImage(Graphics memoryGraphics){
Image img = moveChange.imageChange(fireImage);
memoryGraphics.drawImage(img,this.x,this.y,this.width,this.height,null);
}
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package com.lovo.game.util;
import java.awt.MediaTracker;
import com.lovo.game.role.Fire;
import com.lovo.game.role.GameMap;
import com.lovo.game.role.ZhaoYun;
public class TrackerInit {
public static void initImage(MediaTracker tracker){
//初始化地圖圖片
GameMap.mapImg = CutImage.getSingleImage("image/map.jpg", tracker);
//趙云
ZhaoYun.zyImage = CutImage.cutOneImage("image/boss/playSpear.png",18, 236, 134,tracker);
//火
Fire.fireImage = CutImage.cutOneImage("image/fireImg.png", 6, 283, 161,tracker);
try {
//0組的圖片全部等待加載完畢后,在顯示
tracker.waitForID(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package com.lovo.game.util;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageProducer;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class CutImage {
public static Image[][] cutManyImage(String filePath, int row, int col,
int imageWidth, int imageHight,MediaTracker tracker) {
Image[][] img = new Image[row][col];
ImageIcon imIcon = new ImageIcon(filePath);// 創(chuàng)建圖像數(shù)組對象
Image imgTemp = imIcon.getImage();// 創(chuàng)建源圖像
// 為源 圖象獲取ImageProducer源
ImageProducer sourceProducer = imgTemp.getSource();
for (int i = 0; i row; i++) {
for (int j = 0; j col; j++) {
// 創(chuàng)建圖片分割圖像對象,第一、二個參數(shù)為分割圖像起始坐標。后兩個參數(shù)為圖像大小
CropImageFilter cropImg = new CropImageFilter(j * imageWidth, i * imageHight,imageWidth, imageHight);
ImageProducer imgProducer = new FilteredImageSource(sourceProducer, cropImg);
img[i][j] = new JFrame().createImage(imgProducer);
tracker.addImage(img[i][j], 0);
}
}
return img;
}
public static Image[] cutOneImage(String filePath,int col,
int imageWidth, int imageHight,MediaTracker tracker) {
Image[] img = new Image[col];
ImageIcon imIcon = new ImageIcon(filePath);// 創(chuàng)建圖像數(shù)組對象
Image imgTemp = imIcon.getImage();// 創(chuàng)建源圖像
// 為源 圖象獲取ImageProducer源
ImageProducer sourceProducer = imgTemp.getSource();
for (int j = 0; j col; j++) {
// 創(chuàng)建圖片分割圖像對象,第一、二個參數(shù)為分割圖像起始坐標。后兩個參數(shù)為圖像大小
CropImageFilter cropImg = new CropImageFilter(j * imageWidth, 0,imageWidth, imageHight);
ImageProducer imgProducer = new FilteredImageSource(sourceProducer, cropImg);
img[j] = new JFrame().createImage(imgProducer);
tracker.addImage(img[j], 0);
}
return img;
}
public static Image getSingleImage(String imgPath,MediaTracker tracker){
Image img = new ImageIcon(imgPath).getImage();
tracker.addImage(img, 0);
return img;
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package com.lovo.game.util;
import java.awt.Image;
public class MoveImageChange {
private int count;
private Image img;
private int frequency;
private int loopCount;
public MoveImageChange(int frequency){
this.frequency=frequency;
}
public MoveImageChange(int frequency,int count){
this.frequency=frequency;
this.count = count;
}
public Image imageChange(Image[] images){
if(img==null){//初始圖片為第一張圖片
img=images[0];
}
count++;
if(countfrequency){//當記數(shù)器大于頻率時
count=0;
loopCount++;
if(loopCount = images.length){//圖片下標越界時
loopCount=0;
}
img=images[loopCount];
}
return img;
}
public void setLoopCount(int loopCount){
this.loopCount = loopCount;
}
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package com.lovo.game.role;
import java.awt.Graphics;
import java.awt.Image;
import com.lovo.game.util.MoveImageChange;
public class ZhaoYun {
public static Image[] zyImage;
private int x =600;
private int y =300;
private int width =200;
private int height =130;
private MoveImageChange moveChange = new MoveImageChange(3);
public void drawImage(Graphics memoryGraphics){
Image img = moveChange.imageChange(zyImage);
memoryGraphics.drawImage(img,this.x,this.y,this.width,this.height,null);
一個簡單的范例,不明白追問吧
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MoveAnimationDemo extends JFrame {
public MoveAnimationDemo() {
this.setContentPane(new AnimationPanel());
this.setSize(500, 500);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
/**
* 開始動畫
*/
public void startAnimation() {
// 設定初始條件
x = START_X;
y = START_Y;
// 創(chuàng)建計時器
timer = new Timer(DELAY_TIME, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 每一次延遲過后,調用一次
x += 1;
y += 1;
repaint();
// 滿足結束條件就停止
if (x = END_X || y = END_Y) {
timer.stop();
}
}
});
// 開啟計時器
timer.start();
}
public static void main(String[] args) {
MoveAnimationDemo demo = new MoveAnimationDemo();
demo.setVisible(true);
demo.startAnimation();
}
private class AnimationPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(CIRCLE_COLOR);
g.fillOval(x, y, CIRCLE_SIZE, CIRCLE_SIZE);
}
}
// 圓點顏色
private static final Color CIRCLE_COLOR = Color.RED;
// 圓點大小
private static final int CIRCLE_SIZE = 10;
// 起始位置
private static final int START_X = 50;
private static final int START_Y = 50;
// 終止位置
private static final int END_X = 400;
private static final int END_Y = 400;
// 動畫幀之間的延時,每秒60幀
private static final int DELAY_TIME = 1000 / 60;
// 當前位置
private int x;
private int y;
private Timer timer;
}
import?java.awt.Canvas;
import?java.awt.Color;
import?java.awt.Dimension;
import?java.awt.EventQueue;
import?java.awt.Frame;
import?java.awt.Graphics;
import?java.awt.Graphics2D;
import?java.awt.Image;
import?java.awt.RenderingHints;
import?java.awt.event.KeyEvent;
import?java.awt.event.KeyListener;
import?java.awt.event.WindowAdapter;
import?java.awt.event.WindowEvent;
import?java.awt.image.BufferedImage;
import?java.io.File;
import?java.io.IOException;
import?javax.imageio.ImageIO;
public?class?TestImage?extends?Frame
{
private?static?final?long?serialVersionUID?=?1L;
private?static?boolean?PRESSED?=?false;
private?static?int?pointX?=?0;
private?static?int?pointy?=?200;
private?static?int?RIGHT_GO?=?0;
private?static?int?LEFT_GO?=?0;
private?static?int?DIR?=?0;
private?static?int?ANGLE?=?0;
private?static?int?W?=?50;
private?static?int?H?=?60;
private?_Canvas?canvas?=?null;
public?TestImage?()
{
add?(canvas?=?new?_Canvas?());
setIgnoreRepaint?(true);
requestFocus?();
}
public?class?_Canvas?extends?Canvas?implements?Runnable
{
private?static?final?long?serialVersionUID?=?1L;
private?BufferedImage?bi?=?null;
private?Image?bufferedImage?=?null;
private?Thread?thread?=?null;
private?long?sleepTime?=?10;
public?_Canvas?()
{
try
{
bi?=?ImageIO.read?(new?File?("go.png"));
}
catch?(IOException?e)
{}
setBackground?(Color.BLACK);
requestFocus?();
addKeyListener?(new?KeyListener?()
{
@Override
public?void?keyTyped?(?KeyEvent?e?)
{}
@Override
public?void?keyReleased?(?KeyEvent?e?)
{
RIGHT_GO?=?0;
PRESSED?=?false;
}
@Override
public?void?keyPressed?(?KeyEvent?e?)
{
//?38?40?37?39上下左右
DIR?=?e.getKeyCode?();
PRESSED?=?true;
}
});
}
@Override
public?void?paint?(?Graphics?g?)
{
Graphics2D?g2d?=?(Graphics2D)?g;
g2d.setRenderingHint?(RenderingHints.KEY_INTERPOLATION,?RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.drawImage?(rotateImage?(bi.getSubimage?(RIGHT_GO,?LEFT_GO,?W,?H),?ANGLE,?true),?pointX,?pointy,?W,?H,
this);
g2d.dispose?();
}
@Override
public?void?update?(?Graphics?g?)
{
if?(null?==?bufferedImage)
{
bufferedImage?=?createImage?(getWidth?(),?getHeight?());
}
Graphics?bufferedG?=?bufferedImage.getGraphics?();
bufferedG.clearRect?(0,?0,?getWidth?(),?getHeight?());
paint?(bufferedG);
bufferedG.dispose?();
g.drawImage?(bufferedImage,?0,?0,?this);
g.dispose?();
}
public?void?start?()
{
thread?=?new?Thread?(this);
thread.setName?("TestImage");
thread.setPriority?(Thread.MIN_PRIORITY);
thread.start?();
}
public?synchronized?void?stop?()
{
thread?=?null;
notify?();
}
@Override
public?void?run?()
{
Thread?me?=?Thread.currentThread?();
while?(thread?==?me??!isShowing?()?||?getSize?().width?==?0)
{
try
{
Thread.sleep?(555);
}
catch?(InterruptedException?e)
{
return;
}
}
while?(thread?==?me??isShowing?())
{
if?(PRESSED)
{
try
{
if?(DIR?==?39)
{
RIGHT_GO?=?RIGHT_GO?+?50;
LEFT_GO?=?0;
pointX?=?pointX?+?1;
if?(pointX??420)
{
ANGLE?=?90;
pointX--;
pointy--;
W?=?60;
H?=?50;
}
if?(RIGHT_GO??50)
{
RIGHT_GO?=?0;
}
}
else?if?(DIR?==?37)
{
pointX?=?pointX?-?1;
RIGHT_GO?=?RIGHT_GO?+?50;
LEFT_GO?=?60;
if?(pointX??0)
{
ANGLE?=?-90;
pointX++;
pointy--;
W?=?60;
H?=?50;
}
if?(RIGHT_GO??50)
{
RIGHT_GO?=?0;
}
}
else?if?(DIR?==?38)
{
W?=?50;
H?=?60;
pointy?=?150;
ANGLE?=?0;
RIGHT_GO?=?100;
}
else?if?(DIR?==?40)
{
W?=?50;
H?=?60;
ANGLE?=?0;
pointy?=?200;
RIGHT_GO?=?0;
}
Thread.sleep?(sleepTime);
repaint?();
}
catch?(InterruptedException?e)
{
break;
}
}
else
{
RIGHT_GO?=?RIGHT_GO?+?50;
LEFT_GO?=?0;
pointX?=?pointX?+?1;
if?(RIGHT_GO??50)
{
RIGHT_GO?=?0;
}
if?(pointX??500)
{
pointX?=?0;
}
try
{
Thread.sleep?(sleepTime);
repaint?();
}
catch?(InterruptedException?e)
{
break;
}
}
}
thread?=?null;
}
}
/**
?*?旋轉圖像為指定角度
?*?
?*?@param?degree
?*?@return
?*/
public?static?BufferedImage?rotateImage?(?final?BufferedImage?image,?final?int?angdeg,?final?boolean?d?)
{
int?w?=?image.getWidth?();
int?h?=?image.getHeight?();
int?type?=?image.getColorModel?().getTransparency?();
BufferedImage?img;
Graphics2D?graphics2d;
(?graphics2d?=?(?img?=?new?BufferedImage?(w,?h,?type)?).createGraphics?()?).setRenderingHint?(
RenderingHints.KEY_INTERPOLATION,?RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2d.rotate?(d???-Math.toRadians?(angdeg)?:?Math.toRadians?(angdeg),?w?/?2,?h?/?2);
graphics2d.drawImage?(image,?0,?0,?null);
graphics2d.dispose?();
return?img;
}
public?static?void?main?(?String[]?args?)
{
EventQueue.invokeLater?(new?Runnable?()
{
@Override
public?void?run?()
{
final?TestImage?ti?=?new?TestImage?();
ti.setSize?(new?Dimension?(500,?300));
ti.setLocationRelativeTo?(null);
ti.addWindowListener?(new?WindowAdapter?()
{
@Override
public?void?windowClosing?(?WindowEvent?e?)
{
System.exit?(0);
}
@Override
public?void?windowDeiconified?(?WindowEvent?e?)
{
ti.canvas.start?();
}
@Override
public?void?windowIconified?(?WindowEvent?e?)
{
ti.canvas.stop?();
}
});
ti.setResizable?(false);
ti.canvas.start?();
ti.setVisible?(true);
}
});
}
}
估計你想要的是動畫效果,應該這樣:
new?Thread(){
public?void?run(){
//?動畫代碼:移動、漸變、縮放等
}
}.start();//?另啟線程,防止阻塞當初進程
在你的代碼上修改了一下,運行試試吧
import?java.awt.Graphics;
import?javax.swing.JFrame;
import?javax.swing.JPanel;
public?class?F?extends?JFrame?{
public?F()?{
pan?p?=?new?pan();
this.add(p);
}
public?static?void?main(String[]?args)?{
F?fl?=?new?F();
fl.setSize(400,?400);
fl.setVisible(true);
fl.run();
fl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
int?x,?y;
public?void?run()?{
int?r?=?100;
int?angle?=?0;
while?(true)?{
x?=?(int)?((Math.cos(angle?*?2)?*?Math.PI)?*?r);
y?=?(int)?((Math.sin(angle?*?2)?*?Math.PI)?*?r);
angle++;
repaint();
}
}
class?pan?extends?JPanel?{
public?void?paint(Graphics?g)?{
g.drawLine(200,?200,?200,?250);
g.drawLine(200,?225,?x,?y);
g.drawLine(200,?225,?x,?y);
g.drawLine(200,?250,?180,?300);
g.drawLine(200,?250,?220,?300);
g.drawOval(175,?150,?50,?50);
}
}
}
圖片的位移(下落),可以通過修改圖片的x,y坐標來實現(xiàn), 在Swing/Html中,我們可以使用Timer定時(比如每隔100毫秒)去修改圖片的x,y坐標即可實現(xiàn),
多個圖片都按照一定的軌跡移動,那都按照自己的軌跡的算法,去定時修改x,y坐標即可.
JavaFX是java先進的圖形界面框架, 里面有3D和各種動畫, 所以按照軌跡移動,都能輕松實現(xiàn)
JavaFX參考代碼如下
import?javafx.animation.Animation;
import?javafx.animation.Interpolator;
import?javafx.animation.PathTransition;
import?javafx.animation.RotateTransition;
import?javafx.application.Application;
import?javafx.geometry.Insets;
import?javafx.scene.Group;
import?javafx.scene.Scene;
import?javafx.scene.control.Button;
import?javafx.scene.image.ImageView;
import?javafx.scene.layout.HBox;
import?javafx.scene.shape.MoveTo;
import?javafx.scene.shape.Path;
import?javafx.scene.shape.QuadCurveTo;
import?javafx.stage.Stage;
import?javafx.util.Duration;
public?class?PathAnimateDemo?extends?Application?{
public?static?void?main(String[]?args)?{
launch(args);
}
@Override
public?void?start(Stage?primaryStage)?throws?Exception?{
ImageView?imv=new?ImageView(getClass().getResource("ball.png").toExternalForm());
Path?path?=?new?Path();//?路徑;運動軌跡
MoveTo?mt?=?new?MoveTo(20,?50);
QuadCurveTo?quadTo2?=?new?QuadCurveTo(175,?190,?350,?30);
path.getElements().addAll(mt,?quadTo2);
HBox?hbox?=?new?HBox(10);
Button?btnStart?=?new?Button("開始");
Button?btnPause?=?new?Button("暫停");
Button?btnResume?=?new?Button("繼續(xù)");
Button?btnStop?=?new?Button("結束");
hbox.getChildren().addAll(btnStart,?btnPause,?btnResume,?btnStop);
hbox.setPadding(new?Insets(20));
hbox.setLayoutX(80);
hbox.setLayoutY(230);
Group?root?=?new?Group();
root.getChildren().addAll(imv,?path,?hbox);?//?不添加path.就可以不顯示path了
Scene?scene?=?new?Scene(root,?430,?300);
primaryStage.setTitle("JavaFX");
primaryStage.setScene(scene);
primaryStage.show();
//旋轉動畫設置
RotateTransition?rt=new?RotateTransition(Duration.millis(1000),imv);
rt.setInterpolator(Interpolator.LINEAR);
rt.setFromAngle(0);
rt.setToAngle(360);
rt.setCycleCount(Animation.INDEFINITE);
rt.play();
//路徑動畫設置
PathTransition?pt?=?new?PathTransition(Duration.millis(800),?path,?imv);//?路徑動畫
pt.setCycleCount(Animation.INDEFINITE);
pt.setAutoReverse(true);
btnStart.setOnAction(e?-?{
pt.playFromStart();//?從頭開始播放
});
//----按鈕的響應設置---
btnPause.setOnAction(e?-?{
pt.pause();
});
btnResume.setOnAction(e?-?{
pt.play();?//?播放
});
btnStop.setOnAction(e?-?{
pt.jumpTo(new?Duration(0));//?跳到第0秒處
pt.stop();
});
}
}