Android:在屏幕上移动图像

时间:2014-07-14 07:36:44

标签: android image

我希望用这个程序实现的是,当我的手指触摸图像并且我在屏幕上移动(拖动)它时,图像应该移动,并且一旦我松开手指,图像就应该保持在最后触及的位置。但是,当循环不断更新时,我的图像一直在屏幕上从第一个触摸位置移动到最后一个触摸位置,给我这种效果。

enter image description here

这是MainGamePanel类,它在屏幕上绘制图像:

public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback{

private static final String TAG = MainGamePanel.class.getSimpleName();

private MainThread thread;
private Droid droid;

public MainGamePanel(Context context) {
    super(context);
    getHolder().addCallback(this);
    setFocusable(true);
    thread = new MainThread(getHolder() , this);
    droid = new Droid(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher), 50, 50);
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    // TODO Auto-generated method stub

}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    thread.setRunning(true);
    thread.start();

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    boolean retry = true;
    while(retry)
    {
        try {
            thread.join();
            retry = false;
        } catch (InterruptedException e) { }
    }

}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if(event.getAction() == MotionEvent.ACTION_DOWN)
    {
        droid.handleActionDown((int)event.getX(), (int)event.getY());
        if(event.getY() > getHeight() - 50)
        {
            thread.setRunning(false);
            ((Activity) getContext()).finish();
        }
        else
        {
            Log.d(TAG, "Cords: x = "+event.getX()+" ,y = "+event.getY());
        }
    }
    if(event.getAction() == MotionEvent.ACTION_MOVE)
    {
        if(droid.isTouched())
        {
            droid.setX((int)event.getX());
            droid.setY((int)event.getY());
        }
    }
    if(event.getAction() == MotionEvent.ACTION_UP)
    {
        if(droid.isTouched())
        {
            droid.setTouched(false);
        }
    }
    return true;
}

@Override
protected void onDraw(Canvas canvas) {

    droid.draw(canvas);
}

}

这是Droid类的handleActionDown方法:

public void handleActionDown(int eventX, int eventY)
{
    if(eventX >=(x - bitmap.getWidth()/2) && (eventX <= x + (bitmap.getWidth()/2)))
    {
        if(eventY >=(y - bitmap.getHeight()/2) && (y <= y + (bitmap.getHeight()/2)))
        {
            setTouched(true);
        }else
        {
            setTouched(false);
        }
    }
    else
    {
        setTouched(false);
    }
}

1 个答案:

答案 0 :(得分:0)

您只需在绘制图像之前清除画布。

@Override
public void draw(Canvas canvas) {
    super.draw(canvas);
    //Just call this line
    canvas.drawColor(0, Mode.CLEAR);
    canvas.drawBitmap(mBitmap1,mBitmap1Point.x-(mBitmap1.getWidth()/2),mBitmap1Point.y-(mBitmap1.getHeight()/2),null);
}

对我来说很好。