in my android app I have an ImageView and on top of it I put a custom view, which shows some rectangles. Now I want to zoom into the image by pinching two fingers. Usually that's not a problem but I want the custom View to be zoomed with the same scale factor as the image. I don't have a clue, how to do this. Can someone help me please? Thank you!
1 Answers
You can use the custom ImageView
provided in this answer which supports zoom with pinching, and to get the scale value to be applied your custom view, you need to create a listener with a callback that you can call typically from the onScale()
method of the ScaleListener
like below
interface OnScaleListener {
public onScaleChange(float scaleFactor);
}
OnScaleListener mOnScaleListener;
setScaleListener(OnScaleListener listener) {
this.mOnScaleListener = listener;
}
And then trigger this callback with the value of the mScaleFactor
which reflects how much is the image is zoomed in/out. so you can create an instance of the onScaleListener interface within this class, and trigger its callback onScaleChange()
Here is the inner class of the custom ImageView that handles the pinch zoom.
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
mode = ZOOM;
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
float mScaleFactor = detector.getScaleFactor();
float origScale = saveScale;
saveScale *= mScaleFactor;
if (saveScale > maxScale) {
saveScale = maxScale;
mScaleFactor = maxScale / origScale;
} else if (saveScale < minScale) {
saveScale = minScale;
mScaleFactor = minScale / origScale;
}
if (origWidth * saveScale <= viewWidth
|| origHeight * saveScale <= viewHeight)
matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2,
viewHeight / 2);
else
matrix.postScale(mScaleFactor, mScaleFactor,
detector.getFocusX(), detector.getFocusY());
mOnScaleListener.onScaleChange(mScaleFactor);
fixTrans();
return true;
}
}
And then make your activity or your other custom view implements the OnScaleListener
interface to get the scale value.
Please check this question to zoom-in custom views.

- 37,492
- 7
- 60
- 84