ImageView 数组不保持纵横比

ImageView array not keeping aspect ratio

我有一个小问题,我认为更有经验的人可以轻松解决。在 ImageView 中,我根据需要在 xml 中设置了所有属性,它显示我的图像非常好。然后我决定制作一个 imageView 数组,并在我的应用程序每次发生某些事情时更改图像。这是我之前的 xml,显示效果非常好:

`<ImageView
            android:id="@+id/questions_image_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:adjustViewBounds="true"
            android:contentDescription="@string/image_q1"
            android:layout_margin="16dp"
            android:src="@drawable/view_groups_good"
            android:layout_below="@id/score_no"/>` 

创建数组后,我从 xml 中删除了 android :src 属性并创建了这个方法,每次我想更改图像时都会调用该方法。

这是我在onCreate之前的内容

int [] imageAllQ = {R.drawable.view1, R.drawable.view2, R.drawable.view3, R.drawable.view4, R.drawable.view5, R.drawable.view6, R.drawable.view7, R.drawable.view8, R.drawable.view9, R.drawable.view10};
int imgCount = 0;
ImageView questionsViews;

这是方法:

public void changeImgQA (){
    questionsViews = (ImageView)findViewById(R.id.questions_image_view);
    questionsViews.setBackgroundResource(imageAllQ[imgCount]);
    imgCount = imgCount + 1;
}

一切都如我所愿,但现在图像视图没有考虑 xml 属性并且显示的图像失真,我的意思是它在宽度上与父级匹配但在高度上完全匹配扭曲,与我想要的相比太小了。

欢迎任何建议

使用 scaleType = centerCrop ,这应该保持沿 android:adjustViewBounds="true"

的纵横比

setBackGroundResource ,将背景设置为给定 resource.However setImageBackground,将可绘制对象设置为此 ImageView 的内容。

这就是为什么会出现这种失真。

你应该使用

questionsViews.setImageResource(imageAllQ[imgCount]);

而不是

questionsViews.setBackgroundResource(imageAllQ[imgCount]);

原因

setImageResourceImageView 的 public 方法,负责将 ImageView 的源设置为给定的资源。

Sets a drawable as the content of this ImageView.

setBackgroundResourceView 的 public 方法,负责将 View 的背景设置为给定资源。

Set the background to a given resource. The resource should refer to a Drawable object or 0 to remove the background.

顺便说一句

您应该在 onCreate 中初始化 ImageView 一次,然后重新使用它,而不是每次更改图像时都调用 findViewById