OnTouch Listener doesn't change bitmap location

后端 未结 1 1647
北荒
北荒 2021-01-14 18:30

I have a \"Board.java\" class, which is an activity, and a \"MySurfaceView.java\", which is a SurfaceView. I\'m drawing some bitmap on the

相关标签:
1条回答
  • 2021-01-14 18:40

    Remove TouchListener in Board

    Board:

    public class Board extends AppCompatActivity{
    
    MySurfaceView mv;
    Bitmap bp;
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mv = new MySurfaceView(this);
        bp = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        setContentView(mv);
    
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        mv.pause();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        mv.resume();
    }
    }
    

    And in MySurfaceView

    public class MySurfaceView extends SurfaceView implements Runnable {
    float x, y;
    Bitmap bp;
    Thread t = null;
    SurfaceHolder holder;
    boolean isItOK = false;
    
    
    public MySurfaceView(Context context) {
        super(context);
        Bitmap bpOld = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        bp = Bitmap.createScaledBitmap(bpOld, 250, 250, true);
        x = 0;
        y = 0;
        holder = getHolder();
    }
    
    
    @Override
    public void run() {
        while(isItOK){
            if(!holder.getSurface().isValid())
                continue;
            Canvas c = holder.lockCanvas();
            c.drawARGB(255,150,150,10);
    
            c.drawBitmap(bp,x-(bp.getWidth()/2),y-(bp.getHeight()/2),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 onTouchEvent(MotionEvent event) {
        x = event.getX();
        y = event.getY();
      //  run();
        return super.onTouchEvent(event);
    }
    }
    

    Above work fine for me.

    0 讨论(0)
提交回复
热议问题