在ImageView中拉伸图片

18

我有一个ImageView,它的高度和宽度都设置为“fill_parent”,使用相同值设置的RelativeLayout。
将图片的scaleType设置为"fitXY"

以下是XML布局:

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

适应宽度和高度,但是图片被拉伸了。


这里有一个非常好的解决方案:https://dev59.com/rG445IYBdhLWcg3wZJiw#4886871 - ban-geoengineering
请在android布局文件中使用**android:adjustViewBounds="true"android:scaleType="fitCenter"**。 - Borzh
4个回答

23

这就是fitXY的作用。 如果您不想裁剪图像,则可以尝试使用centerInside,如果您想填充所有空间并裁剪图像,请使用centerCrop

这里有一个很好的列表,其中包含了各种scaleTypes的示例,以帮助更好地理解它们。


19

这两个属性解决了我的问题:

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

0
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);
    }
}

一点解释? - user4974662

0

这就是fitXY的作用。它不会考虑图像的纵横比,而是将图像填充到您的ImageView中,而不保持图像的原始纵横比。如果您想将图像的大小与视图匹配,可以自己缩放图像,或者您可以使用Glide库来完成。在Android中,Glide是一个非常有用的图像库。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接