我在android上绘图有问题。我正在尝试创建简单的游戏,其中包括将以不同颜色绘制屏幕的机器人。首先,我只尝试在没有任何机器人图像的情况下绘制屏幕(我稍后将它放在更高透明视图上)但是我遇到了闪存画布的问题。
所以这是我的渲染方法。在绘图之前我不能每次canvas.drawColor(Color.BLACK);
使用,因为我说机器人需要用自己的颜色(红色和蓝色)绘制屏幕。其他想法是存储每个机器人位置并在每个“渲染”方法上绘制它,但是它需要花费太多时间并且在几秒之后游戏变得非常慢。
public void render(Canvas canvas) {
if(lastD1X!=-1 && lastD1Y!=-1){
canvas.drawLine(lastD1X, lastD1Y, droid.getX(), droid.getY(), drawPaint);
}
lastD1X = droid.getX();
lastD1Y = droid.getY();
if(lastD2X!=-1 && lastD2Y!=-1){
canvas.drawLine(lastD2X, lastD2Y, droid2.getX(), droid2.getY(), drawPaint2);
}
lastD2X = droid2.getX();
lastD2Y = droid2.getY();
}
这是我的游戏循环:
@Override
public void run() {
Canvas canvas;
Log.d(TAG, "Starting game loop");
long beginTime; // the time when the cycle begun
long timeDiff; // the time it took for the cycle to execute
int sleepTime; // ms to sleep (<0 if we're behind)
int framesSkipped; // number of frames being skipped
sleepTime = 0;
while (running) {
canvas = null;
// try locking the canvas for exclusive pixel editing
// in the surface
try {
canvas = this.surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder) {
beginTime = System.currentTimeMillis();
framesSkipped = 0; // resetting the frames skipped
// update game state
this.gamePanel.update();
// render state to the screen
// draws the canvas on the panel
this.gamePanel.render(canvas);
// calculate how long did the cycle take
timeDiff = System.currentTimeMillis() - beginTime;
// calculate sleep time
sleepTime = (int)(FRAME_PERIOD - timeDiff);
if (sleepTime > 0) {
// if sleepTime > 0 we're OK
try {
// send the thread to sleep for a short period
// very useful for battery saving
Thread.sleep(sleepTime);
} catch (InterruptedException e) {}
}
while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS) {
// we need to catch up
this.gamePanel.update(); // update without rendering
sleepTime += FRAME_PERIOD; // add frame period to check if in next frame
framesSkipped++;
}
}
} finally {
// in case of an exception the surface is not left in
// an inconsistent state
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
} // end finally
}
}