1
votes

I am trying to display an image with canvas that allows zoom and panning but will stop the user from panning the image off screen. I have been able to stop the panning but when the picture is zoomed it stops before the edge of the image. I need to be able to pan to the edge of the image even zoomed in. Any help would be appreciated.

My code that displays image, stops the panning offscreen and zoom:

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

        if (mPosX < displayWidth - mIcon.getIntrinsicWidth()){
            mPosX = displayWidth - mIcon.getIntrinsicWidth();}
        if (mPosX > 0){
            mPosX = 0; }
        if (mPosY < displayHeight - mIcon.getIntrinsicHeight()){
            mPosY = displayHeight - mIcon.getIntrinsicHeight();}
        if (mPosY > 0){
            mPosY = 0; }

        canvas.translate(mPosX, mPosY);
        canvas.scale(mScaleFactor, mScaleFactor);
        mIcon.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.42f, Math.min(mScaleFactor, 5.0f));

            invalidate();
            return true;
        }
    }
1
Are you reworking code from Google Blog android-developers.blogspot.com/2010/06/… ? And, what does clipping mPosX/Y to be <= 0 do? - Walter K
Yes, I am mainly reworking that code. The mPosX/Y > 0 has the image stay in the screen on the top and left image borders. The other mPosX/Y section tries to keep the image in the screen along the right and bottom borders of the image but fails to when zoomed in. - Abel8658

1 Answers