Let Volley's NetworkImageView show local image files

前端 未结 3 598
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 00:47

I am using NetworkImageView to show some covers downloaded from a remote URL and I successfully manage to cache and show them, but I want to let users set their

3条回答
  •  时光说笑
    2020-12-09 00:59

    Thank you for your answer. I wrote some code based on your help.

    usage: just use LocalImageCache.class as Cache. No more code to change.

    private ImageLoader mLocalImageLoader;
    
    mLocalImageLoader = new ImageLoader(mRequestQueue,
                new LocalImageCache(mCtx));
    
    NetworkImageView test = (NetworkImageView) findViewById(R.id.iv_test);  
    
    test.setImageUrl("/storage/emulated/0/DCIM/Philm/2017_03_24_01_.png", MySingleton.getInstance(this.getApplicationContext()).getLocalImageLoader());
    

    public class LocalImageCache extends LruCache implements ImageLoader.ImageCache {
    
    public LocalImageCache(int maxSize) {
        super(maxSize);
    }
    
    public LocalImageCache(Context ctx) {
        this(getCacheSize(ctx));
    }
    
    @Override
    public Bitmap getBitmap(String key) {
        key = key.substring(key.indexOf("/"));
        Bitmap result = get(key);
        Log.d("TAG", key);
        if (result == null) {
            Bitmap temp =  BitmapFactory.decodeFile(key);
            put(key, temp);
            return temp;
        } else {
            return result;
        }
    }
    
    @Override
    public void putBitmap(String key, Bitmap bitmap) {
        // Here you can add an actual cache
        // Never touch here
    }
    
    // 默认屏幕5倍的图片缓存
    // Returns a cache size equal to approximately three screens worth of images.
    public static int getCacheSize(Context ctx) {
        final DisplayMetrics displayMetrics = ctx.getResources().
                getDisplayMetrics();
        final int screenWidth = displayMetrics.widthPixels;
        final int screenHeight = displayMetrics.heightPixels;
        // 4 bytes per pixel
        final int screenBytes = screenWidth * screenHeight * 4;
    
        return screenBytes * 5;
    }
    
    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight();
    }
    

    }

提交回复
热议问题