Imageloader-获取图片需要显示的大小

时间:2025-01-31 08:14:59

说一下通过线程加载图片的过程:

  1. 首先根据ImageView获得适当的压缩的宽和高
  2. 然后计算inSampleSize,用于压缩图片
  3. 接着将图片添加到缓存
  4. 最后mUIHandler发送消息更新图片。

第一步 根据ImageView获得适当的压缩的宽和高

因为要获取到压缩的宽和高,方法只能返回一个值,所以我们可以采用内部类的方式将宽和高设置为变量,返回此类的对象即可。

  /**
     * 压缩的宽和高
     */
    private class ImageSize{
        int width ;
        int height;
    }

计算压缩的宽和高的方法

 /**
     * 根据imageView获取适当的压缩的宽和高
     * @param imageView
     */
    private ImageSize getImageViewSize(ImageView imageView) {
        ImageSize imageSize = new ImageSize();
        final DisplayMetrics displayMetrics = ().getResources().getDisplayMetrics();

        final  params = ();

        int width =  == .WRAP_CONTENT ? 0 : imageView
                .getWidth(); // Get actual image width
        if (width <= 0)
            width = ; // Get layout width parameter
        if (width <= 0)
            width = getImageViewFieldValue(imageView, "mMaxWidth"); // Check maxWidth parameter
        if (width <= 0)
            width = ;
        int height =  == .WRAP_CONTENT ? 0 : imageView
                .getHeight(); // Get actual image height
        if (height <= 0)
            height = ; // Get layout height parameter
        if (height <= 0)
            height = getImageViewFieldValue(imageView, "mMaxHeight"); // Check
        // maxHeight
        // parameter
        if (height <= 0)
            height = ;
         = width;
         = height;
        return imageSize;
    }
/**
     * 为了兼容低版本,没有采用@Target()的方式
     * 反射获得ImageView设置的最大宽度和高度
     *
     * @param object
     * @param fieldName
     * @return
     */
    private static int getImageViewFieldValue(Object object, String fieldName)
    {
        int value = 0;
        try
        {
            Field field = (fieldName);
            **(true);**
            int fieldValue = (Integer) (object);
            if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE)
            {
                value = fieldValue;

                ("TAG", value + "");
            }
        } catch (Exception e)
        {
        }
        return value;
    }

相关文章