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

wis*_*slo 5 android-image picasso

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

// 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);
Run Code Online (Sandbox Code Playgroud)

此代码适用于较新的手机,但在具有32MB VM的手机上,我遇到了内存问题.所以我尝试将(2)更改为:

    Picasso.with(context)
       .load(url)
       .fit()
       .into(imgDisplay);
Run Code Online (Sandbox Code Playgroud)

这导致图像失真.由于在下载之前我不知道图像的尺寸,因此我无法设置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" />
Run Code Online (Sandbox Code Playgroud)

处理这种情况的最佳方法是什么?我的原始图像最大宽度为768,高度为1024,我希望在屏幕比这个小得多时进行下采样.如果我尝试使用resize(),我的代码变得复杂,因为我必须等待(1)完成下载然后添加resize()in(2).

我假设转换在这种情况下没有帮助,因为输入public Bitmap transform(Bitmap source)将具有大位图,这将导致我耗尽内存.

Seb*_*ano 5

您可以fit()centerCrop()或结合使用centerInside(),具体取决于您希望图像适合您的方式View:

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

Picasso.with(context)
   .load(url)
   .fit()
   .centerInside()
   .into(imgDisplay);
Run Code Online (Sandbox Code Playgroud)