edi233
edi233

Reputation: 3031

Canvas and drawing picture

How I can draw picture from drawable resources in place where I click? I have onTouch method where I get position where I click but I donlt know how I can draw picture in this coordinates.

Upvotes: 0

Views: 2400

Answers (1)

user901309
user901309

Reputation:

This tutorial is helpful:

http://www.helloandroid.com/tutorials/how-use-canvas-your-android-apps-part-1

Implement what you see there to start.

Then you can update the X and Y coordinates of the image (in the tutorial they are both hardcoded to 10):

    int mXpos = 10;
    int mYpos = 10;

    public void updateXY(int x, int y) {
        mXpos = x;
        mYpos = y;
    }

    @Override
    public void onDraw(Canvas canvas) {

            Paint paint = new Paint();


            Bitmap kangoo = BitmapFactory.decodeResource(getResources(),
                            R.drawable.kangoo);
            canvas.drawColor(Color.BLACK);
            canvas.drawBitmap(kangoo, mXpos, mYpos, null);

    }

You should probably initialize mXpos and mYpos in your constructor, but I've done so here for simplicity in the example.

Then in Canvastutorial's onCreate, add your OnTouchListener:

    mGamePanel = (Panel) this.findViewById(R.id.SurfaceView01);
    mGamePanel.setOnTouchListener(new OnTouchListener(){
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            mGamePanel.updateXY((int)event.getX(), (int)event.getY())
            return true;
    }});

OR, depending on your needs, you can create an ArrayList of X,Y Points and add a new Point each time in onTouch, then in your onDraw method of the canvas you would iterate the canvas.drawBitmap(kangoo, 10, 10, null) line for each point.

Upvotes: 1

Related Questions