Hitendra
Hitendra

Reputation: 3226

Redraw image on canvas on touch event?

I am trying to redraw an image on the canvas on an onTouch event. I am able to draw the image on the canvas, but I want the image to redraw at a particular x,y.

protected void onDraw(Canvas canvas)

{

     mBitmap1   = BitmapFactory.decodeResource(getResources(), R.drawable.ab);
 mBitmap2   = BitmapFactory.decodeResource(getResources(), R.drawable.ab);
 this.canvas=canvas;

     Paint p = new Paint();
    p.setColor(Color.parseColor("#FFFFFF"));

    canvas.drawLine(x1, y1, x2 , y2, p);
    canvas.drawBitmap(mBitmap1, 70, 60, null);
    canvas.drawBitmap(mBitmap1, 185, 60, null);
}


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        final int x=(int)event.getX();
        Log.i("***********xPos","="+x);
        final int y=(int)event.getY();
        Log.i("***********yPos","="+y);

        if(event.getAction()==MotionEvent.ACTION_UP)
        {

        }
        if(event.getAction()==MotionEvent.ACTION_DOWN)
        {
            canvas.drawBitmap(mBitmap1,50+x,60,null );
            this.postInvalidate();

        }
        if(event.getAction()==MotionEvent.ACTION_MOVE)
        {

        }
        return false;
    }

Upvotes: 0

Views: 9785

Answers (2)

chikka.anddev
chikka.anddev

Reputation: 9629

I think I understand your problem. You are calling postinvalidate() method each time when action.down is called, so it calls ultimately call ondraw(). So it will redraw it on bitmap for particular setted value at which you put in ondraw again.

So you looks that it remain unchanged.

Follow these steps:

  1. use some public variables for drawing bitmaps in ondraw method for x and y axis, lets say initx and inity

  2. then on touch event:update this value by adding your x and y value to initx and inity resp.

    like:initx=initx+x;
    inity=inity+y;
    

And last in cation down event just call post.invalidate or ondraw method.

Upvotes: 3

Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28541

See the MotionEvent class that provides the coordinates of where the user touched the screen.

Upvotes: 0

Related Questions