美文网首页首页投稿(暂停使用,暂停投稿)Android
Android开发(31)处理缩略图和解决getWidth为0

Android开发(31)处理缩略图和解决getWidth为0

作者: 张云飞Vir | 来源:发表于2016-06-22 14:46 被阅读434次

    概述

    在开发时,需要显示显示图片的缩略图。使用 ThumbnailUtils.extractThumbnail 可以构建缩略图。
    但是这个方法需要指定ImageView的宽度和高度,我们需要解决如何获得宽度和高度的问题。

    需求

    我有个 imageView ,用于显示图片。
    我使用 asyncTask获得图片,并准备在这个imageView 中显示该图片的缩略图,我准备使用 ThumbnailUtils.extractThumbnail 方法生成缩略图。

    处理缩略图的方法

        ThumbnailUtils.extractThumbnail(source, width, height);  
        这个方法的参数:
         source 源文件(Bitmap类型)
          width  压缩成的宽度
          height 压缩成的高度
    

    这里需要一个宽度和高度的参数,要想再imageView里填满图片的话,这里就应该传入imageView的宽度和高度。

    问题

    我们在 activity的 onCreate,onStart方法,直接调用 imageView.getWidth 方法获得宽度始终为0。

    解决方法

    使用步骤:
    1.先获得imageView 的 一个ViewTreeObserver 对象。

        ViewTreeObserver vto2 = imageView1.getViewTreeObserver()
    

    2.为这个 ViewTreeObserver 对象添加监听器,它需要一个 OnGlobalLayoutListener 类型的参数 。

        vto2.addOnGlobalLayoutListener()
    

    3.实现OnGlobalLayoutListener,在实现的方法里调用 imageView.getWidth 获得宽度。

    代码

    private void showImage(final File resultFileArg) {
            if (resultFileArg != null && resultFileArg.exists()) {
                // 添加下载图片至 imageView
                
              ViewTreeObserver vto2 = imageView1.getViewTreeObserver();
                vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (Build.VERSION.SDK_INT < 16) {
                            imageView1.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        } else {
                            imageView1.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
    
                        Bitmap bm = BitmapFactory.decodeFile(resultFileArg.getPath());
    
                        Bitmap thumbnailImg = ThumbnailUtils.extractThumbnail(bm,
                                imageView1.getMeasuredWidth(),
                                imageView1.getMeasuredHeight());
                        bm.recycle();
                        
                        imageView1.setImageBitmap(thumbnailImg);
                        // imageView1.setImageBitmap(bm);
                    }
                });
            }
        }

    相关文章

      网友评论

        本文标题:Android开发(31)处理缩略图和解决getWidth为0

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