android - 如何使图像适合宽度并在android中保持纵横比

标签 android android-layout imageview android-imageview

我有一个固定高度和宽度的 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/

相关文章:

android - 删除在开发 Android 中安装新版本应用程序时的共享首选项

android - Android错误 “SQLiteException:near ” 1“: syntax error (code1)

android - AdMob AdView 出现了,但我的布局的其余部分不见了 (Android)

android - 启动 Android 导航获取结果

android - 锁定时解锁抽屉布局

android - 用于包装内容的对话框 Activity

android - 如何创建一个包含 2 列的 ListView ,显示所有已安装的 Android 应用程序及其权限?

java - 带有来自特殊 HashMap 的图像的 Android ListView

android - 动态更改 ImageView 背景

android - 识别在 Android 中点击的图像区域?