21

Seems simple, and yet I'm having problems with implementation.

I want a canvas with image on screen including onTouch events. I have tried ImageView but I was not able to use canvas. I have tried SurfaceView and was able to show image in canvas on screen but I have problems with motion onTouch events (zoom, pan).

I need canvas because I will render the image in my code.

Can someone please show me the right way of doing this?

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
no9
  • 6,424
  • 25
  • 76
  • 115

1 Answers1

44

You can use this:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;

public class MyImageView extends View {

private static final int INVALID_POINTER_ID = -1;

    private Drawable mImage;
    private float mPosX;
    private float mPosY;

    private float mLastTouchX;
    private float mLastTouchY;
    private int mActivePointerId = INVALID_POINTER_ID;

    private ScaleGestureDetector mScaleDetector;
    private float mScaleFactor = 1.f;

    public MyImageView(Context context) {
        this(context, null, 0);
    mImage = getResources().getDrawable(R.drawable.imagename);

        mImage.setBounds(0, 0, mImage.getIntrinsicWidth(), mImage.getIntrinsicHeight());
    }

    public MyImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // Let the ScaleGestureDetector inspect all events.
        mScaleDetector.onTouchEvent(ev);

        final int action = ev.getAction();
        switch (action & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN: {
            final float x = ev.getX();
            final float y = ev.getY();

            mLastTouchX = x;
            mLastTouchY = y;
            mActivePointerId = ev.getPointerId(0);
            break;
        }

        case MotionEvent.ACTION_MOVE: {
            final int pointerIndex = ev.findPointerIndex(mActivePointerId);
            final float x = ev.getX(pointerIndex);
            final float y = ev.getY(pointerIndex);

            // Only move if the ScaleGestureDetector isn't processing a gesture.
            if (!mScaleDetector.isInProgress()) {
                final float dx = x - mLastTouchX;
                final float dy = y - mLastTouchY;

                mPosX += dx;
                mPosY += dy;

                invalidate();
            }

            mLastTouchX = x;
            mLastTouchY = y;

            break;
        }

        case MotionEvent.ACTION_UP: {
            mActivePointerId = INVALID_POINTER_ID;
            break;
        }

        case MotionEvent.ACTION_CANCEL: {
            mActivePointerId = INVALID_POINTER_ID;
            break;
        }

        case MotionEvent.ACTION_POINTER_UP: {
            final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) 
                    >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
            final int pointerId = ev.getPointerId(pointerIndex);
            if (pointerId == mActivePointerId) {
                // This was our active pointer going up. Choose a new
                // active pointer and adjust accordingly.
                final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
                mLastTouchX = ev.getX(newPointerIndex);
                mLastTouchY = ev.getY(newPointerIndex);
                mActivePointerId = ev.getPointerId(newPointerIndex);
            }
            break;
        }
        }

        return true;
    }

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

        canvas.save();
        Log.d("DEBUG", "X: "+mPosX+" Y: "+mPosY);
        canvas.translate(mPosX, mPosY);
        canvas.scale(mScaleFactor, mScaleFactor);
        mImage.draw(canvas);
        canvas.restore();
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor();

            // Don't let the object get too small or too large.
            mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));

            invalidate();
            return true;
        }
    }

}
Bjorn
  • 69,215
  • 39
  • 136
  • 164
  • can you please point out how to use this custom view in my activity? I have created layout using this custom view and in my activity i have setContentView(R.layouts.myImageLayout) ... guess thats not enough? – no9 Apr 22 '11 at 05:23
  • to call this setContentView(new MyImageView(this)); & notice that i had removed 1 argument from constructor from MyImageView –  Apr 22 '11 at 05:41
  • i have tried making instance of this class in my activity, but when on draw hits i get blank screen (no image is showing) PS: The constructor MyImageView(MapActivity) is undefined? – no9 Apr 22 '11 at 05:44
  • oh, the code didnt refresh as i was posting comment ... let me try now – no9 Apr 22 '11 at 05:50
  • works now ... thanx alot for helping me hotveryspicy! all the best! – no9 Apr 22 '11 at 05:51
  • do one thing, instead writing mImage = getResources().getDrawable(R.drawable.imagename); write this mImage=act.getResources().getDrawable(context.getResources().getIdentifier("imagename", "drawable", "packagename")); –  Apr 22 '11 at 05:54
  • ohh its pleasure, & from this class u can do many more things, i think this is the best class to work with touch, coz u hav x & y in ur hand –  Apr 22 '11 at 05:59
  • one more thing ... i have intended to render the image in my activity. That means that i have to push a canvas to my renderer in my activity and then draw the rendered image. Since this code only uses canvas in OnDrawn i dont know how to do this... i dont want to render in onDrawn method ... What i need is: empty image on canvas, then push the canvas to renderer so its rendered then show this rendered image fullscreen via extended class u provided with onTouch functionality – no9 Apr 22 '11 at 06:27
  • u want to show random image, passing from ur activity then it will draw in canvas with extends view? –  Apr 22 '11 at 06:38
  • yes. what i have created: I created image (bitmap) from my activity then converted to drawable and pushed to custom view constructor. Works. Next i created this in my activity: empty bitmap. new canvas. new paint. canvas.DrawBitmap(emptyBitmap). Then i pushed this canvas in my renderer where i draw a simple line on this canvas. then i change the bitmap to drawable and push the drawable to extended view ... i hope you understand my confusion :) – no9 Apr 22 '11 at 06:48
  • so u want to modify bitmap by simpleline?, tell me where u stuck exactly? –  Apr 22 '11 at 06:56
  • maybe u are using skype or any other chat? – no9 Apr 22 '11 at 07:09
  • some part of it. Do you happen to know why when i do some rendering on my canvas in "onDraw" method the touch events are not working? If i just display image (withhout any rendering) the events work normaly. – no9 May 05 '11 at 06:03