Search code examples
androidimageviewscale

How to scale an image which should not smaller than a specified size


I'm using a ImageView to dislay an image. There is a "Image--" button, when I click it, the ImageView will use a matrix to scale the image. The problem is, the image will finally too small to see.

You can see my examples.

Original Image:

enter image description here

After clicking button "Image--" 12 times:

enter image description here

You can see the sofa image is so small that hard to see now.

My "main.xml" content is:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/root" xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
        >

    <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"
                  android:orientation="horizontal">
        <!-- buttons -->
    </LinearLayout>

    <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content"
               android:adjustViewBounds="true" android:background="#336699"
               android:scaleType="matrix"/>

</LinearLayout>

And my java code is:

    this.btnImageZoomOut.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Matrix matrix = new Matrix(imageView.getImageMatrix());
            matrix.postScale(0.8f, 0.8f);
            imageView.setImageMatrix(matrix);
            imageInfo();
        }
    });

My question is: how to let the sofa image will smaller a specified size? e.g. 1/5 of original size?


UPDATE

If I can get the size of scaled sofa image, it will be easy to check if the image is too small. But I tried a lot, still not get it, that's why I ask this question. Do I miss something?


Solution

  • I think it might be easier to do it with Layoutparams (which will provide you the size of the image) instead of Matrix since you will need the size anyways. This could be your onClick method for zoom out:

      imageView.setScaleType(ScaleType.FIT_XY);
      LayoutParams layoutParams=imageView.getLayoutParams();
      layoutParams.height*=0.8f;
      layoutParams.width*=0.8f;
      if(layoutParams.height>scaled_specified_size_in_px && layoutParams.width>scaled_specified_size_in_px){
        imageView.setLayoutParams(layoutParams);
      }
    

    Notice that you need to have a scaled value there, OR you can simply limit it to a % of the original size (You will need to save the original size).