TextView加载Html文本显示图片问题

最优实现方案,异步加载图片本人使用ImageLoader,各位也可以使用其他工具加载获得Bitmap类型图片
图片超出view显示宽度时缩放到view显示宽度,否则显示图片在手机中的实际大小


代码——使用kotlin编写

skuDetailsIntroTv.movementMethod = LinkMovementMethod.getInstance()  //设置连接可点击跳转
skuDetailsIntroTv.text = Html.fromHtml(sku.getViewProdIntro(), Html.ImageGetter { source ->
    val drawable = LevelListDrawable()
    ImageLoader.getInstance().loadImage(source, object : ImageLoadingListener {
        override fun onLoadingComplete(imageUri: String?, view: View?, result: Bitmap?) {
            if (result != null) {
                val bitmapDrawable = BitmapDrawable(resources, result)
                //添加一层bitmap
                drawable.addLevel(1, 1, bitmapDrawable)

                //根据手机像素密度重新计算
                val scale = resources.displayMetrics.density
                val bitmapWidth = Math.round(result.width * scale)
                val bitmapHeight = Math.round(result.height * scale)

                //防止图片超出view显示区域宽度
                val viewContentWidth = skuDetailsIntroTv.width - skuDetailsIntroTv.paddingLeft -
                        skuDetailsIntroTv.paddingRight
                val width = if (viewContentWidth < bitmapWidth) viewContentWidth else bitmapWidth
                //等比例缩放
                val height = bitmapHeight * width / bitmapWidth
                drawable.setBounds(0, 0, width, height)
                drawable.level = 1

                //异步加载的drawable需要重新加载,invalidate()无效果,暂时的解决方案
                val text = skuDetailsIntroTv.text
                skuDetailsIntroTv.text = text
                skuDetailsIntroTv.refreshDrawableState()
            }
        }

        override fun onLoadingStarted(imageUri: String?, view: View?) {
        }

        override fun onLoadingCancelled(imageUri: String?, view: View?) {
        }

        override fun onLoadingFailed(imageUri: String?, view: View?, failReason: FailReason?) {
        }
    })
    drawable
}, null)

效果图片展示

TextView加载Html文本显示图片问题_第1张图片


html测试数据——图片url域名做了*处理

<p>
    <span style="font-size:14px;">asdfasfdasdfasfdaspan> 
p>
<p>
    <strong><em><u><span style="color:#E56600;">asfdaslkasfd舒服舒服span>u>em>strong> 
p>
<p>
    lasfsajfdasfdk!@$%!@$#!@$
p>
<p>
    <span style="font-size:24px;background-color:#FFE500;"><strong><u>文本输入u>strong>span> 
p>
<p>
    文本输入
p>
<p>
    本文本
p>
<p>
     
p>
<p>
    <img src="http://test.******.com:6080/hca/api/business/getfile/Z3JvdXAxL00wMC8wMC8xQy93S2hRVzFvb3BSV0FkTGJkQUFBdXRRR2dBNjA3MzY5MDY4"/>
p>

stackoverflow参考链接

你可能感兴趣的:(莫名奇妙)