Canvas image with on touch event

1

I ran into a problem. I need to draw an image (Drawable) on canvas and then be able to move it around the screen with an on touch. The image appears but I can not make it move.

I have this code to make it move that worked well for me when I used it in MainActivity but I can not make it work in the new class I create.

What am I failing? Is this the right way to do it?

Thanks

public class Juego extends View implements View.OnTouchListener {

Drawable esfera;

public Juego(Context context, AttributeSet attrs) {
    super(context, attrs);
    esfera = context.getResources().getDrawable(R.drawable.esfera);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    int ancho = 200;
    int alto = 200;
    esfera.setBounds(0, 0, alto, ancho);
    esfera.draw(canvas);
}

float x,y = 0.0f;
boolean moving = false;
@Override
public boolean onTouch(View v, MotionEvent event) {

    switch(event.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            moving = true;
            break;
        }

        case MotionEvent.ACTION_MOVE: {
            if (moving) {
                x = event.getRawX() - esfera.getWidth() / 2;
                y = event.getRawY() - esfera.getHeight() * 3 / 2;
                esfera.setX(x);
                esfera.setY(y);
            }
            break;
        }

        case MotionEvent.ACTION_UP: {
            moving = false;
            break;
        }
    }
    return true;
}

}

    
asked by Agustin Val 26.05.2017 в 03:24
source

0 answers