借助Bitmap和createBitmap方法可以挖取源位图的一块,这样可以在程序中通过定时器不断的挖取源位图中的不同块,给游戏者一种背景在移动,即对象在向前移动的假象。

import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
public class MoveBack extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
class MyView extends View
{
// 记录背景位图的实际高度
final int BACK_HEIGHT = 1700;
// 背景图片
private Bitmap back;
private Bitmap plane;
// 背景图片的开始位置
final int WIDTH = 480;
final int HEIGHT = 800;
private int startY = BACK_HEIGHT - HEIGHT;
public MyView(Context context)
{
super(context);
back = BitmapFactory.decodeResource(context.getResources(),R.drawable.back_img);
plane = BitmapFactory.decodeResource(context.getResources(),R.drawable.plane);
final Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
if (msg.what == 0x123)
{
// 重新开始移动
if (startY <= 0)
{
startY = BACK_HEIGHT - HEIGHT;
}
else
{
startY -= 3;
}
}
invalidate();
}
};
new Timer().schedule(new TimerTask()
{
public void run()
{
handler.sendEmptyMessage(0x123);
}
}, 0, 100);
}
public void onDraw(Canvas canvas)
{
// 根据原始位图和Matrix创建新图片
Bitmap bitmap2 = Bitmap.createBitmap(back, 0, startY, WIDTH, HEIGHT);
// 绘制新位图
canvas.drawBitmap(bitmap2, 0, 0, null);
// 绘制飞机
canvas.drawBitmap(plane, 160, 360, null);
}
}
}