在制作游戏时,背景可以移动,原理就是 两张图片的循环移动。
package com.example.manager;
import com.example.agame.R;
import com.example.entity.Enemy;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.View;
public class BackgroundManager{
private Bitmap background=null;
private Rect secrect,desrect,desrect2;
private int dy1,dy2;
private int x,y;
public BackgroundManager(View view){
x=view.getWidth();
y=view.getHeight();
dy2=-view.getHeight();
background=BitmapFactory.decodeResource(view.getResources(), R.drawable.background);
secrect=new Rect(0,0,background.getWidth(),background.getHeight());
desrect=new Rect(0,dy1,x,y);
desrect2=new Rect(0,dy2,x,y);
}
public void drawbackground(Canvas canvas){
dy1+=3;
dy2+=3;
desrect.set(0,dy1,x,y+dy1);
desrect2.set(0,dy2,x,y+dy2);
canvas.drawBitmap(background,secrect,desrect,null);//第一张图画在屏幕中央
canvas.drawBitmap(background,secrect,desrect2,null);//第二张图画在屏幕上方
if(dy1>=y)
dy1=-y+3;//为了背景连接和谐
if(dy2>=y)
dy2=-y+4;
}
}
这样就能实现背景循环移动啦!!!