Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android drawing on touch event

I'm trying to make an application which enables user to touch the screen and draw image based on users' finger coordinates. Here's my code :

public class DrawingBoard extends View {

        Drawable editIcon = getResources().getDrawable(R.drawable.icon);
        Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.background);

        float xPos = 0;
        float yPos = 0; 

        public DrawingBoard (Context context) {
            // TODO Auto-generated constructor stub
            super (context);            
        }
        @Override
        protected void onDraw (Canvas canvas) {
            super.onDraw(canvas);

            canvas.save();
            canvas.drawBitmap(mBitmap, 0, 0, null);
            canvas.translate(xPos, yPos);
            editIcon.draw(canvas);
            canvas.restore();

            invalidate();
        }
        @Override
        public boolean onTouchEvent (MotionEvent event) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN : 
                    xPos = event.getX();
                    yPos = event.getY();
                    break;
            }

            return true;

        }
    }
}

But, whenever I try to click on a screen in emulator, there's no image shown....

pls point out my mistake... THX

like image 738
Jason Avatar asked Jul 20 '11 03:07

Jason


1 Answers

You don't have invalidate() in onTouchEvent()

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

            canvas.save();
            canvas.drawBitmap(mBitmap, 0, 0, null);
            canvas.translate(xPos, yPos);
            editIcon.draw(canvas);
            canvas.restore();

       //     invalidate();
        }
        @Override
        public boolean onTouchEvent (MotionEvent event) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN : 
                    xPos = event.getX();
                    yPos = event.getY();
                    invalidate(); // add it here
                    break;
            }

            return true;

        }
like image 199
yushulx Avatar answered Oct 23 '22 14:10

yushulx