美文网首页
用TextView显示Html图片

用TextView显示Html图片

作者: 刀鱼z | 来源:发表于2017-11-02 10:54 被阅读0次

前言,对于一些项目中要实现图文混排,我看到有的项目中直接嵌入了一个webview加载h5页面...个人觉得非常不好

个人觉得用TextView显示比较好,当然我们要做适当的优化

实现 Html.ImageGetter

public class MyImageGetter implements Html.ImageGetter {
    @Override
    public Drawable getDrawable(String s) {
        return null;
    }
}

重写getDrawable方法

    public Drawable getDrawable(final String picUrl) {
        Drawable drawable;
        File file = new File(mFilePath, picUrl.hashCode() + "");
        if (file.exists()) {
            drawable = getDrawableFromDisk(file);
        } else {
            drawable = getDrawableFromNet(picUrl);
        }
        return drawable;
    }

先从本地缓存找,如果本地没有,就从网络获取,网络获取成功后保存本地

 File file = new File(mFilePath, picUrl.hashCode() + "");
    InputStream in = null;
    FileOutputStream out = null;
    try {
        in = response.byteStream();
        out = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        return true;
    } catch (Exception e) {
        return false;
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
        }
    }

,
mFilePath是存储的路径,picUrl的hashcode值是文件名,获取后存到本地指定路径下

private Drawable getDrawableFromDisk(File file) {
    Drawable drawable = Drawable.createFromPath(file.getAbsolutePath());
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());        
    return drawable;
}

这是从本地读取图片,如果你需要对图片进行等比例压缩,那么在初始化MyImageGetter的时候,传图片的宽度过来,获取到drawable后,对drawable进行计算高度,根据宽度进行等比例压缩放大 Drawable的getIntrinsicWidth()和getIntrinsicHeight()返回图片的实际高度宽度(dp)

最后调用

    TextView.setText(Html.fromHtml(sText, imageGetter, null));    

相关文章

网友评论

      本文标题:用TextView显示Html图片

      本文链接:https://www.haomeiwen.com/subject/fvropxtx.html