调整大小后使 imageView 适合图像大小

Fit imageView to image size after resizing it

我正在实现一个叫做 InApp 消息的东西,现在我试图在调整大小后使 ImageView 适合图像大小。

这是我的图片视图:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:layout_marginStart="15dp"
    android:layout_marginTop="40dp"
    android:padding="6dp">

   --other components--

    <ImageView
        android:id="@+id/middleLayoutImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/border"
        android:padding="5dp"
        app:layout_constraintBottom_toTopOf="@+id/middleLayoutText"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/topWrapper"
        app:layout_constraintVertical_chainStyle="packed" />

   --other components--

</android.support.constraint.ConstraintLayout> 

要下载 img 并放入此视图,我使用的是 Picasso:

        Picasso.with(getApplicationContext())
            .load(inputurl)
            .into(imageView);

现在我的 activity 看起来像这样: Before fitting

现在我想根据父布局的宽度调整其纵横比。我尝试了很多 od 组合但没有成功:

以及与 android:adjustViewBounds scaleTypes 等的更多组合

我想实现这样的目标:Resized correctly - 在这种情况下,我使用了 picasso:.resize(2000,500).centerInside() - 但它仅在这种情况下有效。 .如何自动完成? 在此先感谢您的帮助:)

编辑:

    ImageView imageView = (ImageView) findViewById(R.id.middleLayoutImage);

    String inputurl = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSQtqf1EUqH4eQNNqYFbSawpiR5bypfOhvlatgS0mC3Ve1nk2adbw"; //http://www.gatesms.eu/img/android.png";
    Picasso.with(getApplicationContext())
            .load(inputurl)
            .resize(2000,500)
            .centerInside()
            .into(imageView);

为了 Picasso 正确适合您的 Image,您应该知道 Image 的尺寸。但是对于这种情况,您不知道图像的大小,那么为了 UI 设计,您应该有一个占位符(毕加索正在加载另一个图像时显示的图像)将该图像保存在您的 drawable 文件夹中让将其命名为 placeholder 并将其设置为 src 或者像这样使用 Picasso 本身:

Picasso.with(getActivity()) 
.load(imageUrl) 
.placeholder(R.drawable.placeholder) 
.error(R.drawable.error) 
.resize(screenWidth, imageHeight)
.fit()
.centerCrop() 
.into(imageView);

现在怎么办?

现在因为你在 imageView 中有另一个 Image Picasso 现在知道高度和宽度所以它可以很好地适合你的图像。但是,如果您不提供任何图像,那么结果将是非常小的图像或拉伸不当的图像。我还添加了一个可选的错误图像,如果 Picasso 未能像我那样发出请求,它将被替换为没有网络连接,如果你愿意,你可以省略它。

别忘了 XML 中的 android:adjustViewBounds