我是安卓新手。我想绘制用户触摸的位图。这会在触摸时创建一个位图,但只会创建一个位图,并且当用户触摸时,它会被替换并移动到新位置。我想在新的触摸位置上绘制一个新的位图,将旧的位图留在原位,并且可以将任何位图移动/拖动到新位置..请帮助
public class SurfaceViewEx extends Activity implements OnTouchListener {
OurView v;
Bitmap cloud;
float x, y;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
cloud = BitmapFactory.decodeResource(getResources(), R.drawable.cloud);
v = new OurView(this); //Passing the context of this class
v.setOnTouchListener(this);
x = y = 0;
setContentView(v);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
v.pause();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
v.resume();
}
//It will handle drawing
public class OurView extends SurfaceView implements Runnable {
Thread t = null;
SurfaceHolder holder; //
boolean isItOk = false;
public OurView(Context context) {
super(context);
//To make sure we can draw on canvas and surface is valid
holder = getHolder();
}
@Override
public void run() {
// TODO Auto-generated method stub
while (isItOk == true) {
//Perform canvas drawing
if(!holder.getSurface().isValid()) {
//Call back to while ..
continue;
}
//Lock the canvas, and unlock after drawing
Canvas c = holder.lockCanvas();
c.drawARGB(255, 0, 0, 0);
c.drawBitmap(cloud, x - (cloud.getWidth()/2), y - (cloud.getHeight()/2), null);
holder.unlockCanvasAndPost(c);
}
}
public void pause() {
isItOk = false;
while(true) {
try {
//Blocks the current thread until the receiver finishes
//the execution and dies
t.join();
}
catch (InterruptedException e){
e.printStackTrace();
}
break;
}
//t = null;
}
public void resume() {
isItOk = true; //Able to draw
t = new Thread(this);
t.start();
}
}
@Override
public boolean onTouch(View v, MotionEvent me) {
// TODO Auto-generated method stub
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
switch(me.getAction()) {
case MotionEvent.ACTION_DOWN:
x = me.getX();
y = me.getY();
break;
case MotionEvent.ACTION_UP:
//Same code
case MotionEvent.ACTION_MOVE:
//Same code
}
return true;
}
}