根据此question,我使用了一个自定义ImageGatter类,以使用Picasso在TextView中显示从服务器获取的图像
public class PicassoImageGetter implements Html.ImageGetter {
private TextView textView = null;
Context mContext;
public PicassoImageGetter() {
}
public PicassoImageGetter(TextView target, Context context) {
textView = target;
mContext = context;
}
@Override
public Drawable getDrawable(String source) {
BitmapDrawablePlaceHolder drawable = new BitmapDrawablePlaceHolder();
Picasso.get().load(source).into(drawable);
return drawable;
}
private class BitmapDrawablePlaceHolder extends BitmapDrawable implements com.squareup.picasso.Target {
protected Drawable drawable;
@Override
public void draw(final Canvas canvas) {
if (drawable != null) {
drawable.draw(canvas);
}
}
public void setDrawable(Drawable drawable) {
this.drawable = drawable;
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
drawable.setBounds(0, 0, width, height);
setBounds(0, 0, width, height);
if (textView != null) {
textView.setText(textView.getText());
}
}
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
setDrawable(new BitmapDrawable(mContext.getResources(), bitmap));
}
@Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
setDrawable(errorDrawable);
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
}
并以此方式使用
imageGetter = new PicassoImageGetter(contentTextView, this);
Spannable html;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
html = (Spannable) Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY, imageGetter, null);
} else {
html = (Spannable) Html.fromHtml(content, imageGetter, null);
}
contentTextView.setText(html);
如果没有连接,我需要将这些图像捕获到内部或外部存储中以显示它,但是我不知道路径或文件名。
答案 0 :(得分:4)
您需要自己实现毕加索缓存。应该是这样的:
public class PicassoCache {
private static Picasso picassoInstance = null;
private PicassoCache(Context context) {
Downloader downloader = new OkHttp3Downloader(context, Integer.MAX_VALUE);
Picasso.Builder builder = new Picasso.Builder(context);
builder.downloader(downloader);
picassoInstance = builder.build();
}
public static Picasso getPicassoInstance(Context context) {
if (picassoInstance == null) {
new PicassoCache(context);
return picassoInstance;
}
return picassoInstance;
}
}
然后在您的代码中:
@Override
public Drawable getDrawable(String source) {
BitmapDrawablePlaceHolder drawable = new BitmapDrawablePlaceHolder();
PicassoCache.getPicassoInstance(getContext()).load(source).into(drawable);
return drawable;
}
OkHttp3Downloader
将图像缓存安装到您的应用程序缓存目录中。您还可以将另一个构造函数与您自己提供的目录public OkHttp3Downloader(final File cacheDir, final long maxSize)
您也可以使用Glide。这就像毕加索一样,但也可以让您以动画和缓存策略显示gif,恕我直言,这有点容易。
Glide.with(context)
.load(source)
.apply(RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL))
.into(drawable)