Search code examples
androidandroid-activityzoomingandroid-viewgestures

Zooming an activity


So I have spent a number of hours searching the web for help but all forums and documentation has not properly explained to me the best way I should go about this.

Currently I have an activity with an XML relative layout (the background is set to a picture of a map) and I would like to implement a multi-gesture zoom feature. After a lot of reading it seems that I should be using ScrollGestureDetector which must be implemented inside a view.

I would like to make it so that the user can use a 2 pointer gesture anywhere on the screen and it will zoom in. The issue is that I don't know how to implement this and cannot find resources to show me how to do this to an activity.

Is there any way I can implement ScrollGestureDetector for my RelativeLayout? Should I create a custom view that covers the entire screen and presents the picture so that I can implement ScrollGestureDetector in the class definition? How should I go about this?


Solution

  • Using pinch-zoom to scale an image works best if the image is within an ImageView. The ImageView can scale images arbitrarily while background images are scaled based only on the view bounds.

    You just need to call setContentView() on your activity with a layout that contains an ImageView.

    To use ScaleGestureDetector in your code, you have to do the following

    1. Declare a ScaleGestureDetector in your view.

      private ScaleGestureDetector mScaleGestureDetector;
      
    2. Initialize it with your scaling event listener, preferable in onCreate():

      mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleGestureDetector.OnScaleGestureListener() {
          @Override
          public boolean onScale(ScaleGestureDetector detector) {
              // your impl here
              return false;
          }
      
          @Override
          public boolean onScaleBegin(ScaleGestureDetector detector) {
              // your impl here
              return false;
          }
      
          @Override
          public void onScaleEnd(ScaleGestureDetector detector) {
              // your impl here
          }
      })
      
    3. Add the ScaleGestureDetector to your onTouchEvent() method:

      @Override
      public boolean onTouchEvent(MotionEvent event) {
      
          mScaleGestureDetector.onTouchEvent(event);
      
          // do other stuff
          return super.onTouchEvent(event);
      }
      

    Strangely, ScaleGestureDetector.onTouchEvent() always returns true, but you can use isInProgress() to tell if a scaling operation has started.