【问题标题】:Resize ImageView's height to match original image's aspect ratio using Glide使用 Glide 调整 ImageView 的高度以匹配原始图像的纵横比
【发布时间】:2020-05-15 01:14:23
【问题描述】:

我在GridLayout 中有一个ImageView,它显示了从 URL 加载的图像。 GridLayout 有 2 列,并且全部拉伸到整个屏幕。我需要在不改变纵横比的情况下看到整个图像。由于屏幕宽度在许多设备上可能有所不同,因此我需要根据ImageView 的宽度(需要填充 GridLayout)和下载图像的纵横比来计算高度。

我的想法是将ImageViewwidth 设置为match_parent,将height 设置为wrap_content,然后告诉Glide我想计算高度以适应图像的纵横比,但我正在努力做到这一点。

到目前为止,我的布局中有这个:

<ImageView
    android:id="@+id/list_item_image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scaleType="fitCenter" />

这在适配器中:

Glide.with(viewHolder.imageView.getContext())
                    .load(item.getImageUrl())
                    .apply(new RequestOptions().error(R.color.black_one))
                    .into(viewHolder.imageView);

【问题讨论】:

    标签: android imageview android-glide


    【解决方案1】:

    我在article 中找到了解决方案。使用 ConstraintLayout 可以选择使用 app:layout_constraintDimensionRatio 参数。您需要将其中一个维度设置为 0dp,然后您只需选择所需的任何比例即可。

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:src="@drawable/top_image"
            app:layout_constraintDimensionRatio="16:9"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"/>
    
    </android.support.constraint.ConstraintLayout>
    

    【讨论】:

      【解决方案2】:

      我相信您正在寻找的是像 instagram 提要那样加载图像,具有固定宽度的动态高度,而不裁剪内容。然后设置高度以包裹内容,宽度以匹配父项并将 adjustViewBounds 设置为 true。

        <ImageView
              android:id="@+id/imageView"
              android:layout_width="0dp"
              android:layout_height="wrap_content"
              android:adjustViewBounds="true"
              android:minHeight="200dp"
              app:layout_constraintEnd_toEndOf="parent"
              app:layout_constraintStart_toStartOf="parent" />
      

      android:adjustViewBounds 参数具有动态设置图像视图高度的魔力。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-22
        • 1970-01-01
        • 1970-01-01
        • 2014-08-01
        • 2021-12-23
        • 2013-04-05
        相关资源
        最近更新 更多