6

I am having a problem in zooming the canvas. I have made a customized view in which I am drawing relationship diagrams now when I zoom out the canvas in goes to the position (0,0). I have seen different threads and questions but could not find appropriate answer.

What i am doing in onDraw Method is.

  canvas.scale(mScaleFactor, mScaleFactor);

I have also seen the canvas.scale(x, y, px, py) method but i do not know how to get the pivot points of x and y.

public boolean onScale(ScaleGestureDetector detector) {

mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.4f, Math.min(mScaleFactor, 5.0f));
if(mScaleFactor>=1)
   mScaleFactor=1f; 

invalidate();
return true;

}

user229044
  • 232,980
  • 40
  • 330
  • 338
sajjoo
  • 6,576
  • 20
  • 65
  • 86

2 Answers2

11

The pivot points are basically the point that your canvas will be transformed around, so scaling with a pivot of 0,0 makes it shrink towards that point. using the following method you can change the pivot point to wherever you want it:

canvas.scale(x, y, px, py);

Now for the new stuff: If you want your canvas to be scaled towards its centre, you will just have to know the point in the middle of your canvas:

float cX = canvas.getWidth()/2.0f; //Width/2 gives the horizontal centre
float cY = canvas.getHeight()/2.0f; //Height/2 gives the vertical centre

And then you can scale it using those coordinates:

canvas.scale(x, y, cX, cY);
Jave
  • 31,598
  • 14
  • 77
  • 90
  • This makes my image on the center of the screen. – sajjoo Jan 13 '12 at 12:23
  • Where do you want the scaling to be centered? – Jave Jan 13 '12 at 12:27
  • i want to scale the area between my fingers and it should be scaled on the same point. like google map does. – sajjoo Jan 13 '12 at 14:01
  • 1
    In that case you'd have to get both the touched points, and calculate the centre from those: `cX = Math.abs(point1.getX() - point2.getX())/2; cY = Math.abs(point1.getY() - point2.getY())/2;` – Jave Jan 13 '12 at 14:04
  • got the mid points and gave it to canvas.scale(x, y, cX, cY); but still its not working. ;( – sajjoo Jan 16 '12 at 07:03
  • 1
    The only thing I can think of is if the canvas does not have its top left corner at the top left corner of the screen. Then the coordinates might have to be offset to match the canvas... :S – Jave Jan 16 '12 at 12:37
  • Thank you for the detailed walk through of the approach, Jave. – Sipty Jul 01 '15 at 15:46
-1

Take a look at these two answers, they describe the problem and its solutions very well.

Android Bitmap/Canvas offset after scale

Scaling image of ImageView while maintaining center point in same place

Community
  • 1
  • 1
Anders Metnik
  • 6,096
  • 7
  • 40
  • 79