Mary June
Mary June

Reputation: 159

How to make image fit the whole screen in android?

I tried to make image taken to fit the whole screen size. My XML for the activity layout is below:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

My code to display the image:

private void showImage(String imageName){
    String directory = "/sdcard/DCIM/cat/" + imageName;
    File  imageFile = new File(directory);
    if(imageFile.exists()){
        Bitmap imageBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());

        //rotating the bitmap by 90 degree clockwise. Assume the bitmap is 270 degree clockwise.
        Matrix mtx = new Matrix();
        mtx.preRotate(90);

        int w = imageBitmap.getWidth();
        int h = imageBitmap.getHeight();

        imageBitmap = Bitmap.createBitmap(imageBitmap,0,0,w,h,mtx,false);
        imageBitmap = imageBitmap.copy(Bitmap.Config.ARGB_8888,true);
        ImageView imageView = (ImageView)findViewById(R.id.imageView1);
        imageView.setImageBitmap(imageBitmap);

    }

The output on the scree is as below: Screen capture of the activity

As you all might observe, there are blank spaces at both left and right side of the image. Any way to make the image fit perfectly onto the screen?

Upvotes: 1

Views: 3591

Answers (4)

Anand Soni
Anand Soni

Reputation: 186

Use either

android:scaleType = "fitCenter" //This will preserve the aspect ratio of image

or

android:scaleType="fitXY" //This won't preserve the aspect ratio of image

Upvotes: 1

Eugen Pechanec
Eugen Pechanec

Reputation: 38241

Add android:scaleType="centerCrop" to the <ImageView> declaration. It will fill the whole space and cut off extra parts.

Upvotes: 4

Hareshkumar Chhelana
Hareshkumar Chhelana

Reputation: 24848

Use android:scaleType properties fill image :

android:scaleType="fitXY"

OR

imageView.setScaleType(ImageView.ScaleType.FIT_XY)

Upvotes: 3

Naruto Uzumaki
Naruto Uzumaki

Reputation: 2087

With setScaleType attribute you can do it.

something like this:

imgView.setScaleType(ImageView.ScaleType.FIT_CENTER); // OR FIT_XY

Upvotes: 1

Related Questions