Search code examples
androidcoordinateszoomingpicassoandroid-photoview

PhotoView - Keep zoom and the xy coordinates


I am using PhotoView Picasso on my Android application. I want to toggle two images by clicking a button, keeping the zoom and the xy coordinates. I can keep the zoom, but it is hard to keep the xy coordinates because two images have different resolutions and I have to keep the relative xy coordinates AFTER the zoom. When I toggle to a new image, if I don't keep the xy coordinates, the zoomed image is always at the center. Below is my current code, which only implements keeping the zoom.

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {

    // ... some basic stuffs here

    mRequestCreator1 = Picasso.get().load(mImageUri1);
    mRequestCreator2 = Picasso.get().load(mImageUri2);
    mRequestCreator1.into(mPhotoView);

    mBtnSwitch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final float prevScale = mPhotoView.getScale();
            // MUST use the callback because of timing issue.
            Callback callback = new Callback() {
                @Override
                public void onSuccess() { mPhotoView.setScale(prevScale); }

                @Override
                public void onError(Exception e) { e.printStackTrace(); }
            };

            if(sPrevIsOriginal) {
                mRequestCreator2.into(mPhotoView, callback);
            } else {
                mRequestCreator1.into(mPhotoView, callback);
            }
            sPrevIsOriginal = !sPrevIsOriginal;
        }
    });
}

Solution

  • After a lot of trials and errors, I found out how to do it. You have to get the supplementary matrix of the previous image by using getSuppMatrix(), and then apply that supplementary matrix to the new image by using setSuppMatrix(). It's important to use supplementary matrix. NEVER try to do this by manipulating getImageMatrix() or getDisplayMatrix(), cause it either will not work or the code will become a lot more complex.