美文网首页
基础模块封装 -- 图片加载

基础模块封装 -- 图片加载

作者: TomyZhang | 来源:发表于2020-05-24 15:59 被阅读0次

一、图片加载管理类

public class ImageLoader {

    private static final String CACHE_DIR_NAME = "providerImages";
    private static volatile ImageLoader instance;
    private Picasso picasso;

    private static final int MIN_NORMAL_MEMORY_CACHE_SIZE = 4 * 1024 * 1024;
    private static final int MIN_NORMAL_DISK_CACHE_SIZE = 8 * 1024 * 1024;

    private ImageLoader(Context context){
        Picasso.Builder builder = new Picasso.Builder(context);
        if (BuildConfig.DEBUG && Build.TYPE.equalsIgnoreCase("eng")) {
            builder.loggingEnabled(true)
                    .indicatorsEnabled(true);
        }
        builder.memoryCache(new LruCache(MIN_NORMAL_MEMORY_CACHE_SIZE));
        File cacheDir = context.getDir(CACHE_DIR_NAME, Context.MODE_PRIVATE);
        builder.downloader(new OkHttp3Downloader(cacheDir, MIN_NORMAL_DISK_CACHE_SIZE)).build();
        picasso = builder.build();
        Picasso.setSingletonInstance(picasso);
        if (Build.TYPE.equalsIgnoreCase("eng")) {
            picasso.setLoggingEnabled(true);
        }
    }

    public static ImageLoader with(Context context) {
        if (instance == null) {
            synchronized (ImageLoader.class) {
                if (instance == null) {
                    instance = new ImageLoader(context);
                }
            }
        }
        return instance;
    }

    public ImageRequest url(String url){
        return new ImageRequest(picasso.load(url));
    }

    public ImageRequest uri(Uri uri){
        return new ImageRequest(picasso.load(uri));
    }

    public void cancelTag(Object tag){
        picasso.cancelTag(tag);
    }

    public void removeCache(String imageUri) {
        picasso.invalidate(imageUri);
    }
}

二、图片加载封装类

public class ImageRequest {

    private RequestCreator requestCreator;
    private int placeholderResId;
    private Drawable placeholderDrawable;

    ImageRequest(@NonNull RequestCreator requestCreator){
        this.requestCreator = requestCreator;
    }

    @WorkerThread
    public @Nullable Bitmap fetch(){
        try {
            return requestCreator.get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void fetch(final ImageCallback callback){
        requestCreator.fetch(new Callback() {
            @Override
            public void onSuccess() {
                if (callback != null) {
                    AppExecutor.executeInIO(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                callback.onSucceed(requestCreator.get());
                            } catch (Exception e) {
                                callback.onFailed(getPlaceholderDrawable());
                            }
                        }
                    });
                }
            }

            @Override
            public void onError(Exception e) {
                AppExecutor.executeInIO(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null) {
                            callback.onFailed(getPlaceholderDrawable());
                        }
                    }
                });
            }
        });
    }

    public void fetch(ImageView imageView){
        requestCreator.into(imageView);
    }

    public ImageRequest size(int targetWidth, int targetHeight){
        requestCreator.resize(targetWidth, targetHeight);
        return this;
    }

    public ImageRequest size(ImageSize imageSize) {
        return this.size(imageSize.getWidth(), imageSize.getHeight());
    }

    public ImageRequest placeholder(int placeholderResId) {
        if (this.placeholderDrawable != null) {
            return this;
        }
        this.placeholderResId = placeholderResId;
        requestCreator.placeholder(placeholderResId);
        return this;
    }

    public ImageRequest placeholder(Drawable placeholderDrawable) {
        if (this.placeholderResId != 0) {
            return this;
        }
        this.placeholderDrawable = placeholderDrawable;
        requestCreator.placeholder(placeholderDrawable);
        return this;
    }

    public ImageRequest error(int errorResId) {
        requestCreator.error(errorResId);
        return this;
    }

    public ImageRequest error(Drawable errorDrawable) {
        requestCreator.error(errorDrawable);
        return this;
    }

    public ImageRequest centerCrop() {
        requestCreator.centerCrop();
        return this;
    }

    public ImageRequest centerInside() {
        requestCreator.centerInside();
        return this;
    }

    public ImageRequest fit() {
        requestCreator.fit();
        return this;
    }

    /** Rotate the image by the specified degrees. */
    public ImageRequest rotate(float degrees) {
        requestCreator.rotate(degrees);
        return this;
    }

    public ImageRequest tag(Object tag) {
        requestCreator.tag(tag);
        return this;
    }

    public ImageRequest config(Bitmap.Config config) {
        requestCreator.config(config);
        return this;
    }

    public ImageRequest memoryCache(MemoryPolicy memoryPolicy){
        switch (memoryPolicy){
            case NO_CACHE:
                requestCreator.memoryPolicy(com.squareup.picasso.MemoryPolicy.NO_CACHE);
                break;
            case NO_STORE:
                requestCreator.memoryPolicy(com.squareup.picasso.MemoryPolicy.NO_STORE);
                break;
            default:break;
        }
        return this;
    }

    public ImageRequest diskCache(NetworkPolicy networkPolicy){
        switch (networkPolicy){
            case NO_CACHE:
                requestCreator.networkPolicy(com.squareup.picasso.NetworkPolicy.NO_CACHE);
                break;
            case NO_STORE:
                requestCreator.networkPolicy(com.squareup.picasso.NetworkPolicy.NO_STORE);
                break;
            case OFFLINE:
                requestCreator.networkPolicy(com.squareup.picasso.NetworkPolicy.OFFLINE);
                break;
            default:
                break;
        }
        return this;
    }

    private Drawable getPlaceholderDrawable() {
        if (placeholderResId != 0) {
            if (Build.VERSION.SDK_INT >= 21) {
                return SReminderApp.getInstance().getDrawable(placeholderResId);
            } else {
                return SReminderApp.getInstance().getResources().getDrawable(placeholderResId);
            }
        } else {
            return placeholderDrawable; // This may be null which is expected and desired behavior.
        }
    }
}

三、图片大小封装类

public class ImageSize {
    private static final int TO_STRING_MAX_LENGHT = 9;
    private static final String SEPARATOR = "x";
    private final int width;
    private final int height;

    public ImageSize(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public ImageSize(int width, int height, int rotation) {
        if (rotation % 180 == 0) {
            this.width = width;
            this.height = height;
        } else {
            this.width = height;
            this.height = width;
        }

    }

    public int getWidth() {
        return this.width;
    }

    public int getHeight() {
        return this.height;
    }

    public ImageSize scaleDown(int sampleSize) {
        return new ImageSize(this.width / sampleSize, this.height / sampleSize);
    }

    public ImageSize scale(float scale) {
        return new ImageSize((int)((float)this.width * scale), (int)((float)this.height * scale));
    }

    @Override
    public String toString() {
        return (new StringBuilder(TO_STRING_MAX_LENGHT)).append(this.width).append(SEPARATOR).append(this.height).toString();
    }
}

四、内存缓存策略类

public enum MemoryPolicy {
    /** Default Config*/
    DEFAULT(0),
    /** Skips memory cache lookup when processing a request. */
    NO_CACHE(1 << 0),
    /**
     * Skips storing the final result into memory cache. Useful for one-off requests
     * to avoid evicting other bitmaps from the cache.
     */
    NO_STORE(1 << 1);

    final int index;

    private MemoryPolicy(int index) {
        this.index = index;
    }
}

五、磁盘缓存策略类

public enum NetworkPolicy {
    /** Default config */
    DEFAULT(0),

    /** Skips checking the disk cache and forces loading through the network. */
    NO_CACHE(1 << 0),

    /**
     * Skips storing the result into the disk cache.
     * <p>
     * <em>Note</em>: At this time this is only supported if you are using OkHttp.
     */
    NO_STORE(1 << 1),

    /** Forces the request through the disk cache only, skipping network. */
    OFFLINE(1 << 2);

    final int index;

    private NetworkPolicy(int index) {
        this.index = index;
    }
}

六、图片加载回调类

public interface ImageCallback {
    void onSucceed(Bitmap bitmap);
    void onFailed(@Nullable Drawable placeHolder);
}

相关文章

网友评论

      本文标题:基础模块封装 -- 图片加载

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