我正在为安卓开发游戏。在阶段之间,我想显示带有路线的地图的一部分,并将其从一个城市移动到另一个城市(舞台到舞台)。
首先我想在我的手机上做,这是三星 Galaxy Y,240x320 Qvga ldpi。
所以我有jpg格式的地图文件。这张图片是 2463x602,这是一张世界地图。我做到了,一切都完成了,除了一件事。这个“动画”对我来说很慢。
当我从这个开始时,我想,它会很快,我会用 Thread.sleep(); 但问题是,它并不快。
我怎样才能让它更快呢?这是我的代码:
package hu.mycompany.myproject;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MapActivity extends Activity {
DrawView drawView;
SoundPool soundPool;
int soundId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
soundId = soundPool.load(this, R.raw.airplane, 1);
drawView = new DrawView(this);
setContentView(drawView);
}
public void playSound() {
soundPool.play(soundId, 1f, 1f, 1, 0, 1f);
}
@Override
public void onResume() {
super.onResume();
playSound();
drawView.resume();
}
@Override
public void onPause() {
super.onPause();
drawView.pause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_map, menu);
return true;
}
public class DrawView extends SurfaceView implements Runnable {
Bitmap gameMap = null;
Thread gameLoop = null;
SurfaceHolder surface;
Rect rect;
volatile boolean running;
volatile boolean moved;
public DrawView(Context context) {
super(context);
moved = false;
surface = getHolder();
gameMap = BitmapFactory.decodeResource(getResources(),
R.drawable.map);
}
public void resume() {
running = true;
gameLoop = new Thread(this);
gameLoop.start();
}
public void pause() {
running = false;
while (true) {
try {
gameLoop.join();
} catch (InterruptedException e) {
}
}
}
@Override
public void run() {
Rect canvasSize = new Rect(0, 0, 240, 320);
Paint paint = new Paint();
paint.setAntiAlias(true);
while (running) {
if (!surface.getSurface().isValid()) {
continue;
}
if (!moved) {
int i;
for (i = 80; i <= 830; i++) {
Canvas canvas = surface.lockCanvas();
rect = new Rect(i, 250, (i + 240), 570);
canvas.drawBitmap(gameMap, rect, canvasSize, paint);
surface.unlockCanvasAndPost(canvas);
}
moved = true;
}
}
}
}
}