How to scale an Image in ImageView in Android

In this android programming code example, we are going to illustrate how to scale an image in ImageView in android.

Android ImageView has an attribute called scaleTypethat can take any of the following values

CENTER – Center the image in the view, but perform no scaling.

CENTER_CROP – Scale the image uniformly (maintain the image’s aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding).

CENTER_INSIDE – Scale the image uniformly (maintain the image’s aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).

FIT_CENTER –  Scale the image using Matrix.ScaleToFit.CENTER.

FIT_END – Scale the image using Matrix.ScaleToFit.END.

FIT_START-Scale the image using Matrix.ScaleToFit.START.

FIT_XY –  Scale the image using Matrix.ScaleToFit.FILL.

MATRIX-Scale using the image matrix when drawing.

Add ScaleType in XML layout

ImageView scale can be achieved by assigning the scaleTypeattribute to an ImageView in XML layout file like below

activity.main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <ImageView
        android:id="@+id/imageView2"
        android:scaleType="fitCenter"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/camera"/>

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="centerCrop"
        android:layout_marginTop="30dp"
        android:src="@drawable/camera"/>

</LinearLayout>

Scale Image in ImageView Programmatically

MainActivity.java

import android.os.Bundle;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView imageView= findViewById(R.id.imageView3);
        //This sets the ScaleType to FitXY programmatically
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
    }
}

android imageview scaleType

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment