developer
developer

Reputation: 437

Stretch image in ImageView

I have an ImageView that has its height and width set to "fill_parent" with a Relative Layout that has the same values set.Set Image scaleType="fitXY"

Here The XML layout:

<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">


<ImageView
    android:id="@+id/imageView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scaleType="fitXY"
    android:src="@drawable/background_image" />


</RelativeLayout>

Fits the width and height but the image is stretched.

Upvotes: 18

Views: 33695

Answers (4)

sourav saha
sourav saha

Reputation: 41

That is what fitXY will do. It will not respect the aspect ratio of the image and fill the image to your imageview without maintaining the original aspect ratio of the image. If you want to match size of your image to your view ,you can scale your image yourself or you can look glide library to do that for you . Glide is a very useful library when it comes to image in android

Upvotes: 0

Enrichman
Enrichman

Reputation: 11337

That's what fitXY is supposed to do. You can try with centerInside if you don't want to crop your image, or centerCrop if you want to fill all the space (and cropping your image).

Here is a nice list with examples to understand better all the scaleTypes.

Upvotes: 23

Navneet Boghani
Navneet Boghani

Reputation: 17

package utils;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by Navneet Boghani on 7/7/16.
 */
public class ProportionalImageView extends ImageView {

    public ProportionalImageView(Context context) {
        super(context);
    }

    public ProportionalImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ProportionalImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Drawable d = getDrawable();
        if (d != null) {
         //   int w = MeasureSpec.getSize(widthMeasureSpec);
          //  int h = w * d.getIntrinsicHeight() / d.getIntrinsicWidth();
            int h = MeasureSpec.getSize(heightMeasureSpec);
            int w = h * d.getIntrinsicWidth() / d.getIntrinsicHeight();
            setMeasuredDimension(w, h);
        }
        else super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

Upvotes: 0

Akinola Olayinka
Akinola Olayinka

Reputation: 861

These two properties solved issue for me:

android:scaleType="fitXY"
android:adjustViewBounds="true"

Upvotes: 18

Related Questions