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;
}
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);
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