如何使用onTouchListener检测画布图纸或位图上的单击?

时间:2013-03-27 03:11:04

标签: android canvas bitmap ontouchevent ontouchlistener

此游戏的目标类似于泡泡弹出游戏。每次触摸气泡时,都会发生交互/事件。

到目前为止,这就是我所拥有的。这有点凌乱,因为我是新手,但我的教授告诉我使用onTouch(查看v,运动事件),在那个方法中,我会使用像event.getSource();让我能够与服务于可触摸绘图/位图图像的方法创建交互。

任何建议或帮助都会很棒!非常感谢。

public class MainActivity extends Activity implements OnTouchListener {

OurView v;
Bitmap icon1, icon2, icon3;
float x,y;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    v = new OurView(this);
    v.setOnTouchListener(this);
    icon1 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    icon2 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    icon3 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    x = y = 0;
    setContentView(v);
}

@Override
protected void onPause() {
    super.onPause();
    v.pause();
}

@Override
protected void onResume() {
    super.onResume();
    v.resume();
}


public class OurView extends SurfaceView implements Runnable {

    Thread t = null;
    SurfaceHolder holder;
    boolean isItOK = false;

    public OurView(Context context) {
        super(context);
        holder = getHolder();
    }

    @Override
    public void run() {
        while (isItOK == true){
            if (!holder.getSurface().isValid()){
                continue;
            }
            Canvas c = holder.lockCanvas();
            c.drawARGB(255, 100, 120, 10);
            c.drawBitmap(icon1, x=50, y=100, null);
            c.drawBitmap(icon2, x=180, y=100, null);
            c.drawBitmap(icon3, x=310, y=100, null);
            holder.unlockCanvasAndPost(c);
        }
    }

    public void pause() {
        isItOK = false;
        while(true){
            try{
                t.join();
            }catch (InterruptedException e){    
                e.printStackTrace();
                }
            break;
            }
        t = null;
    }

    public void resume(){
        isItOK = true;
        t = new Thread(this);
        t.start();
    }
}


@Override
public boolean onTouch(View v, MotionEvent me) {

    try {
        Thread.sleep(50);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    me.getSource();


    switch(me.getAction()){
    case MotionEvent.ACTION_DOWN:
        x = me.getX();
        y = me.getY();
        break;
    case MotionEvent.ACTION_UP:
        break;
    case MotionEvent.ACTION_MOVE:

        break;
    }
    return true;
}

}

2 个答案:

答案 0 :(得分:0)

尝试创建一个条件,其中init检查xy是否位于循环内的位图矩形,是否位于位图的矩形内?

答案 1 :(得分:0)

您正在以已知坐标绘制位图,为什么不进行范围检查?例如。如果x> 50和x< 100和y> 100和y< 150然后他们点击了图标1(假设你的位图是50x50) 几秒钟前通过暴徒