2
我在android上製作了一個遊戲,其中一個圖像和你必須拖動它並移動它。但是,當我拖動它的圖像被拖動的路徑上創建了幾個圖像。請看我的代碼和幫助android canvas.drawbitmap()圖像不斷重複
package com.saad.alien;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class Game extends Activity implements OnTouchListener {
CustomView Cview;
float x, y, left = 0, top = 0, right = 0, bottom = 0;
float dx, dy;
Bitmap man;
int done = 0;
RectF rman = new RectF(50, 50, 150, 150);
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Cview = new CustomView(this);
Cview.setOnTouchListener(this);
x = 50;
y = 600;
dx = dy = 0;
man = BitmapFactory.decodeResource(getResources(), R.drawable.man);
setContentView(Cview);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Cview.pause();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Cview.resume();
}
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// x = event.getX();
// y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
dx = event.getX();
dy = event.getY();
float length = x + man.getWidth();
float height = y + man.getHeight();
if (dx > x && dx < length && dy > y && dy < height) {
done = 1;
}
break;
case MotionEvent.ACTION_MOVE:
if (done == 1) {
x = event.getX();
y = event.getY();
}
break;
case MotionEvent.ACTION_UP:
if (done == 1) {
x = event.getX();
y = event.getY();
done = 0;
}
break;
}
return true;
}
public class CustomView extends SurfaceView implements Runnable {
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = false;
public CustomView(Context context) {
super(context);
ourHolder = getHolder();
}
public void pause() {
isRunning = false;
while (true) {
try {
ourThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume() {
isRunning = true;
ourThread = new Thread(this);
ourThread.start();
}
public void run() {
while (isRunning) {
if (!ourHolder.getSurface().isValid())
continue;
Canvas can = ourHolder.lockCanvas();
left = x;
right = (x + man.getWidth());
top = y;
bottom = (y + man.getHeight());
rman.set(left, top, right, bottom);
can.drawBitmap(man, null, rman, null);
ourHolder.unlockCanvasAndPost(can);
}
}
}
}
我想你需要http://stackoverflow.com/questions/5729377/android-canvas-how-do-i-clear-delete-contents-of- a-canvas-bitmaps-livin。檢查答案。 –