我有一个固定高度和宽度的 ImageView(比如宽度为 100dp,高度为 50dp)。我需要将图像动态加载到此 ImageView 。
我希望此图像以填充 ImageView 宽度的方式缩放,但要保持纵横比(我不在乎是否由于高度限制图像的一部分不可见)。
我想要的非常类似于centerCrop
,但我不希望我的图像垂直居中!
提前致谢。
编辑1:
这是我的代码:
这是我的布局。我想使用 background
id 为 imageView 设置图像。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/background"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/footer"
android:layout_alignBottom="@id/footer"
/>
<RelativeLayout
android:id="@+id/footer"
android:layout_width="match_parent"
android:layout_height="100dp">
</RelativeLayout>
注意 imageView 绑定(bind)到第二个 RelativeLayout 的大小:
android:layout_alignTop="@+id/footer"
android:layout_alignBottom="@id/footer"
最佳答案
首先在你的布局中添加
android:scaleType="matrix"
到您的 imageView。
然后在你的 java 代码中添加:
ackground.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Bitmap backgroundBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.background_image);
float imageRatio = (float) backgroundBitmap.getWidth() / (float) backgroundBitmap.getHeight();
int imageViewWidth = background.getWidth();
int imageRealHeight = (int) (imageViewWidth / imageRatio);
Bitmap imageToShow = Bitmap.createScaledBitmap(backgroundBitmap, imageViewWidth, imageRealHeight, true);
background.setImageBitmap(imageToShow);
}
});
我会为你分解它:
在 java 代码中,您创建一个具有所需宽度(您的 imageView 宽度)的 Bitmap 对象并将其设置为您的 imageView。但是你需要让你的 imageView scaleType 变成矩阵来防止 android 自动缩放它!
关于android - 如何使图像适合宽度并在android中保持纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40189968/