下载图像并调整大小以避免OOM错误,毕加索fit()扭曲图像



我正在尝试在全屏视图中显示图像并使用以下代码:

// Target to write the image to local storage.
Target target = new Target() {
   // Target implementation.
}
// (1) Download and save the image locally.
Picasso.with(context)
       .load(url)
       .into(target);
// (2) Use the cached version of the image and load the ImageView.
Picasso.with(context)
       .load(url)
       .into(imgDisplay);

此代码在较新的电话上效果很好,但是在带有32MB VM的手机上,我摆脱了内存问题。所以我尝试将(2)更改为:

    Picasso.with(context)
       .load(url)
       .fit()
       .into(imgDisplay);

这导致了扭曲的图像。由于我在下载图像之前不知道图像的尺寸,因此我无法设置ImageView尺寸,因此,在没有考虑到我的ImageView的远处比率:

的情况下,正在调整图像的大小。
    <ImageView
    android:id="@+id/imgDisplay"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scaleType="fitCenter"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

处理这种情况的最佳方法是什么?我的原始图像具有最大宽度768和高度1024,当屏幕远小于此时,我想下样本。如果我尝试使用resize(),我的代码就会变得复杂,因为我必须等待(1)完成下载,然后在(2)中添加resize()

我假设转换在这种情况下没有帮助,因为public Bitmap transform(Bitmap source)的输入已经具有大的位图,这会导致我无法记忆。

您可以将fit()centerCrop()centerInside()结合,具体取决于您希望图像适合您的View

Picasso.with(context)
   .load(url)
   .fit()
   .centerCrop()
   .into(imgDisplay);
Picasso.with(context)
   .load(url)
   .fit()
   .centerInside()
   .into(imgDisplay);

最新更新