android富文本append网络图片的加载方案
先占位,加载完之后重绘view
val builder = SpannableStringBuilder() val width = DpUtil.dp2px(35) val height = DpUtil.dp2px(30) val drawable = URLImageSpanParser(context, view).getDrawable(bean.url_img, width, height) val imgSpan = CenterAlignImageSpan(drawable) val spannableString = SpannableString("aaaa") spannableString.setSpan( imgSpan, 0, spannableString.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) builder.append(spannableString) builder.append(" ") textView.setText(builder)
用到的工具类
class URLImageSpanParser(val context : Context?, val tv: TextView?) { fun getDrawable(url:String?, width:Int, height:Int): Drawable { var urlDrawable = UikitURLDrawable() if(width == 0){ }else{ urlDrawable.setBounds(0, 0,width, height) } loadDrawableAsync(urlDrawable, url, width, height) return urlDrawable } private fun loadDrawableAsync(urlDrawable : UikitURLDrawable, url:String?, width: Int, height: Int){ ImgLoader.displayDrawable(context, url, object : DrawableCallback { override fun onLoadSuccess(drawable: Drawable) { drawable.setBounds(0, 0, width, height) urlDrawable.drawable = drawable urlDrawable.invalidateSelf() tv?.postInvalidate() } override fun onLoadFailed() { } }) } } class UikitURLDrawable:BitmapDrawable(){ var drawable:Drawable? = null override fun draw(canvas: Canvas) { if(drawable != null){ drawable?.draw(canvas) } } }
public class CenterAlignImageSpan extends ImageSpan { public CenterAlignImageSpan(Drawable drawable) { super(drawable); } public CenterAlignImageSpan(Bitmap b) { super(b); } @Override public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { Drawable b = getDrawable(); Paint.FontMetricsInt fm = paint.getFontMetricsInt(); int transY = (y + fm.descent + y + fm.ascent) / 2 - b.getBounds().bottom / 2;//计算y方向的位移 canvas.save(); canvas.translate(x, transY);//绘制图片位移一段距离 b.draw(canvas); canvas.restore(); } }
public static void displayDrawable(Context context, String url, final DrawableCallback callback) { if (context == null || TextUtils.isEmpty(url)) { return; } try { Glide.with(context).asDrawable().load(new GlideUrl(url, sHeaders)).skipMemoryCache(SKIP_MEMORY_CACHE).into(new SimpleTarget<Drawable>() { @Override public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) { if (callback != null) { callback.onLoadSuccess(resource); } } @Override public void onLoadFailed(@Nullable Drawable errorDrawable) { if (callback != null) { callback.onLoadFailed(); } } }); } catch (Exception e) { e.printStackTrace(); } }
参考文章:Android 使用ImageSpan加载网络图片-CSDN博客
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ri-ji/68564.html