Android TextView加载HTMl图文时,图片溢出界面问题解决

一、问题

在之前一篇博文中介绍了利用TextView加载Html图文,使用的时ImageGetter来加载图片,但是并没有处理图片过大的情况。解决思路是将Bitmap进行尺寸压缩,另外还要注意修改了图片大小会出现图文重叠的问题。

二、解决过程

具体思路就是先获取TextView的宽度width,然后计算出width与 resource.getWidth()的比例。

 float scale = width / resource.getWidth();

利用这个去算出新的图片宽高。

    int afterWidth = (int) (resource.getWidth() * scale);
    int afterHeight = (int) (resource.getHeight() * scale);

这里需要注意数据类型的转换,防止精度损失。

总体的代码如下:
重新的getDrawable方法:

 @Override
    public Drawable getDrawable(String source) {
        final UrlDrawable drawable = new UrlDrawable();
        Glide.with(context)
                .load(source)
                .asBitmap()
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        float width = textView.getWidth();
                        if (resource.getWidth() > width) {
                            float scale = width / resource.getWidth();
                            int afterWidth = (int) (resource.getWidth() * scale);
                            int afterHeight = (int) (resource.getHeight() * scale);
                            drawable.setBounds(0, 0, afterWidth, afterHeight);
                            drawable.setBitmap(BitmapUtil.resizeBitmap(resource, afterWidth, afterHeight));
                        } else {
                            drawable.setBounds(0, 0, resource.getWidth(), resource.getHeight());
                            drawable.setBitmap(resource);
                        }
                        textView.invalidate();
                        textView.setText(textView.getText());
                    }
                });
        return drawable;
    }

另外尺寸压缩的方法:

public static Bitmap resizeBitmap(Bitmap bitmap, int w, int h)
    {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        float scaleWidth = ((float) w) / width;
        float scaleHeight = ((float) h) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        return Bitmap.createBitmap(bitmap, 0, 0, width,
                height, matrix, true);
    }

这里是使用Matrix将Bitmap压缩到指定大小。
这样图片就会宽度适应textView的宽度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值