我在Android上制作游戏,其中有一个图像,你必须拖动并移动它。然而,当我拖动它时,在拖动图像的路径上创建了几个图像。请查看我的代码和帮助
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);
}
}
}
}
答案 0 :(得分:0)
在绘制之前,您需要在每个帧上清除画布。
例如:
Canvas.drawColor(Color.BLACK)