Android Picasso“fit()。centerCrop()”无法加载图片

时间:2017-05-13 22:03:16

标签: android android-imageview picasso

当我使用此代码部分时,我想根据宽度大小将图像(URL)显示为我的imageview中的最大宽度和可变高度:

imageView = (ImageView) convertView.findViewById(R.id.imageView);
Picasso.with(context).load(product.getImage()).into(imageView);

我可以将我的图像显示到imageview中。我也尝试使用 resize()。centerCrop()方法,并且它成功运行。

但是,当我使用

  

Picasso.with(上下文).load(product.getImage())拟合()centerCrop()代入(ImageView的);

  

Picasso.with(上下文).load(product.getImage())拟合()centerInside()代入(ImageView的);

我的imageview什么都没显示。我不明白为什么。也许问题是我的列表设计和imageview。这是我的 list_content_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:weightSum="1">

    <ImageView 
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.80"
        app:srcCompat="@mipmap/ic_launcher" />

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="1"
        android:layout_weight="0.2"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/tv_title"
            android:layout_width="match_parent"
            android:layout_weight="0.3"
            android:layout_height="match_parent" />
        <TextView
            android:id="@+id/tv_stats"
            android:layout_weight="0.7"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"/>

    </LinearLayout>

</LinearLayout>

我尝试将 wrap_content match_parent 设置为ImageView的宽度和高度,但它也没有用。我在哪里错过了?提前谢谢。

3 个答案:

答案 0 :(得分:6)

adjustViewBounds可以解决问题:

android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerCrop"

我发现使用XML属性而不是Picasso方法更容易配置此行为。

答案 1 :(得分:0)

首先,在使用.之前,您没有添加fit()。 用这个替换你的代码:  Picasso.with(context).load(product.getImage()).fit().centerCrop().into(imageView

作为替代品 您还可以使用android:scaleType="fitXY"为imageView定义缩放类型 在youn xml文件中。

然后将您的图片转换为imageview:Picasso.with(context).load(product. getImage).fit().into(imageView);

答案 2 :(得分:0)

公共生成器调整大小(int targetWidth,int targetHeight)

将图像调整为指定大小(以像素为单位)。 使用0作为所需尺寸来调整尺寸以保持宽高比。

使用它。

fun Fragment.getDeviceWidth(): Int {
    val displayMetrics = DisplayMetrics()
    requireActivity().windowManager.defaultDisplay.getRealMetrics(displayMetrics)

    return displayMetrics.widthPixels
}


.resize(getDeviceWidth(), 0)