Подтвердить что ты не робот

Растянуть изображение для подгонки

src должен растягивать свою ширину до match_parent, сохраняя соотношение сторон. Когда изображение больше родительского, оно масштабируется правильно. Но когда изображение меньше, оно не масштабируется. (иллюстрация показывает желаемое поведение).

enter image description here

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/banner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"
        android:adjustViewBounds="true"
        android:src="@drawable/foo"
        />

</RelativeLayout>


Использование ScaleType.fitXY растягивает только width

4b9b3361

Ответ 1

Я считаю, что это невозможно, по крайней мере, не с параметрами, предоставляемыми атрибутом scaleType.
Ваш лучший вариант в этом случае - использовать centerCrop, но только центр изображения будет виден.

Однако, если вы не в порядке с этой опцией, вы можете масштабировать изображение программно, не теряя пропорции. Для этого вам нужно будет рассчитать масштабный коэффициент, основанный на ширине экрана, а затем использовать этот масштабный коэффициент, чтобы узнать новую высоту изображения.

Вот так:

ImageView imageView = (ImageView)findViewById(R.id.imageView);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.foo);

int imageWidth = bitmap.getWidth();
int imageHeight = bitmap.getHeight();

int newWidth = getScreenWidth(); //this method should return the width of device screen.
float scaleFactor = (float)newWidth/(float)imageWidth;
int newHeight = (int)(imageHeight * scaleFactor);

bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
imageView.setImageBitmap(bitmap);

Кроме того, вам нужно настроить объявление ImageView в файле макета:

<ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

Ответ 2

setContentView(R.layout.activity_main);

ImageView imageView = (ImageView)findViewById(R.id.imageView);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);

int imageWidth = bitmap.getWidth();
int imageHeight = bitmap.getHeight();

DisplayMetrics metrics = this.getResources().getDisplayMetrics();

int newWidth = metrics.widthPixels;
float scaleFactor = (float)newWidth/(float)imageWidth;
int newHeight = (int)(imageHeight * scaleFactor);

bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
imageView.setImageBitmap(bitmap);

Разметка

<ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scaleType="centerInside"
    android:src="@drawable/image" />

Ответ 3

android:adjustViewBounds="true" выполняет задание!

Ответ 4

Обычно я использую следующий класс в XML, когда мне нужно это поведение:

Конечно, я иногда настраиваю его в соответствии с некоторыми требованиями. Но мне легче изменить класс из ImageView в другой класс в XML вместо java-кода в контексте представления.

package shush.android.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * @author Sherif elKhatib
 *
 * ImageView Class that maintains the width of the view and changes height to keep the aspect ratio.
 */
public class AspectImageView extends ImageView {

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

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

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if(getBackground() == null || getBackground().getIntrinsicHeight()==0 || getBackground().getIntrinsicWidth()==0) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = width * getBackground().getIntrinsicHeight() / getBackground().getIntrinsicWidth();
        setMeasuredDimension(width, height);
    }
    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    @Override
    public void setImageBitmap(Bitmap bm) {
        if(bm == null)
            return;
        BitmapDrawable bd = new BitmapDrawable(getContext().getResources(), bm);
        if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
            setBackground(bd);
        else
            setBackgroundDrawable(bd);
    }
}

Ответ 5

Объединить два блестящих ответа (этот и этот в быстрое решение. Надеюсь, это спасет кого-то ненужное время исследований!

private Bitmap getScaledBitmap(int resource) {
    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int width = displaymetrics.widthPixels;

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resource);

    float scaleFactor = (float) width / (float) bitmap.getWidth();
    int newHeight = (int) (bitmap.getHeight() * scaleFactor);

    return Bitmap.createScaledBitmap(bitmap, width, newHeight, true);
}

Используйте его следующим образом:

imageView.setImageBitmap(getScaledBitmap(R.drawable.banner_home_2));

Ответ 6

используйте этот MainImage.setScaleType(ImageView.ScaleType.FIT_XY);

ИЛИ вы можете просто добавить android:scaleType="fitXY" в xml.

Ответ 8

ли:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/banner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="centerCrop"
        android:adjustViewBounds="true"
        android:src="@drawable/foo" />
</RelativeLayout>

Не делай, что хочешь?