★40.Glide

2017-06-29  本文已影响0人  iDragonfly

前言

在写本教程时, Glide 的版本号是3.7。

简介

相关概念

简单示例

创建Glide

Glide.with(this)
        .load(/* 加载源 */)
        .into(imageView);

Glide的简单配置项

Glide的复杂配置项

缩略图

简介

简单的缩略图加载

.thumbnail(0.1f)

独立的缩略图加载

DrawableRequestBuilder<String> thumbnailRequest = Glide
        .with(context)
        .load(eatFoodyImages[2]);
.thumbnail(thumbnailRequest)

错误调试

简介

1. 创建RequestListener

RequestListener<String, GlideDrawable> errorListener = new RequestListener<String, GlideDrawable>() {
    @Override
    public boolean onException(Exception e, String model, Target<GlideDrawable> target,
                               boolean isFirstResource) {
        Log.e("onException", e.toString() + "  model:" + model + " isFirstResource: " + isFirstResource);
        imageView.setImageResource(R.mipmap.ic_launcher);
        return false;
    }

    @Override
    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target,
                                   boolean isFromMemoryCache, boolean isFirstResource) {
        Log.e("onResourceReady", "isFromMemoryCache:" + isFromMemoryCache + "  model:" + model
                + " isFirstResource: " + isFirstResource);
        return false;
    }
};

2. 绑定RequestListener

.listener(errorListener)

加载图片到通知

加载图片到应用小控件

缓存

简介

缓存策略

缓存失效【Todo】

官方教程

自定义Target

SimpleTarget

简介

1. 创建SimpleTarget

SimpleTarget target = new SimpleTarget<Bitmap>(/* 长 */, /* 宽 */) {
    @Override
    public void onResourceReady(Bitmap bitmap, GlideAnimation glideAnimation) {
        // 获取到bitmap
        imageView1.setImageBitmap(bitmap);
    }
};

2. 绑定SimpleTarget

// noinspection unchecked
Glide
        .with(context)      // 如果是在Activity生命周期外请求的话,需要使用application context。
        .load(url)
        .asBitmap()         // 通过asBitmap(),避免当资源是视频等,会出现未知格式的情况。
        .into(target);

ViewTarget

简介

1. 创建ViewTarget

ViewTarget<MyView, GlideDrawable> viewTarget = new ViewTarget<MyView, GlideDrawable>(customView) {
    @Override
    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
        this.view.setImage(resource.getCurrent());
    }
};

2. 绑定ViewTarget

.into(target)

自定义BitmapTransformation

1. 定义BitmapTransformation

public class BlurTransformation extends BitmapTransformation {
    private RenderScript rs;

    public BlurTransformation(Context context) {
        super(context);
        rs = RenderScript.create(context);
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        Bitmap blurredBitmap = toTransform.copy(Bitmap.Config.ARGB_8888, true);

        // 分配内存
        Allocation input = Allocation.createFromBitmap(
                rs,
                blurredBitmap,
                Allocation.MipmapControl.MIPMAP_FULL,
                Allocation.USAGE_SHARED
        );
        Allocation output = Allocation.createTyped(rs, input.getType());

        // Load up an instance of the specific script that we want to use.
        ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        script.setInput(input);

        // Set the blur radius
        script.setRadius(10);

        // Start the ScriptIntrinisicBlur
        script.forEach(output);

        // Copy the output to the blurred bitmap
        output.copyTo(blurredBitmap);

        toTransform.recycle();
        return blurredBitmap;
    }

    @Override
    public String getId() {
        return "blur";
    }
}

2. 应用变换

Glide Modules

简介

1. 定义GlideModules

GlideModules外壳

public class SimpleGlideModule implements GlideModule {
    @Override public void applyOptions(Context context, GlideBuilder builder) {
        // todo
    }

    @Override public void registerComponents(Context context, Glide glide) {
        // todo
    }
}

重写applyOptions()

1. 自定义内存缓存

MemorySizeCalculator calculator = new MemorySizeCalculator(context);
int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
int defaultBitmapPoolSize = calculator.getBitmapPoolSize();

int customMemoryCacheSize = (int) (1.2 * defaultMemoryCacheSize);
int customBitmapPoolSize = (int) (1.2 * defaultBitmapPoolSize);

builder.setMemoryCache(new LruResourceCache(customMemoryCacheSize));
builder.setBitmapPool(new LruBitmapPool(customBitmapPoolSize));

2. 自定义磁盘缓存

int cacheSize100MegaBytes = 104857600;
builder.setDiskCache(new InternalCacheDiskCacheFactory(context, cacheSize100MegaBytes));
// builder.setDiskCache(new ExternalCacheDiskCacheFactory(context, cacheSize100MegaBytes));
int cacheSize100MegaBytes = 104857600;
String downloadDirectoryPath = Environment.getDownloadCacheDirectory().getPath();
builder.setDiskCache(new DiskLruCacheFactory(downloadDirectoryPath, cacheSize100MegaBytes));
// 子目录
// builder.setDiskCache(new DiskLruCacheFactory(downloadDirectoryPath, "glidecache", cacheSize100MegaBytes));

3. 自定义图片质量

builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);
// builder.setDecodeFormat(DecodeFormat.PREFER_RGB_565);

4. 其他

重写registerComponents()

使用OkHttp实现从Https中加图片

工具类:OkHttpUrlLoaderOkHttpStreamFetcher

glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(httpsOkHttpClient));

2. 注册

AndroidManifest.xml 中:

<application>
    ...
    <meta-data
            android:name=".SimpleGlideModule"
            android:value="GlideModule"/>
</application>

Glide Transformations

简介

简单示例

单个转换

Glide.with(this).load(R.drawable.demo)
        .bitmapTransform(new BlurTransformation(context))
        .into((ImageView) findViewById(R.id.image));

多个转换

Glide.with(this).load(R.drawable.demo)
        .bitmapTransform(new BlurTransformation(context, 25), new CropCircleTransformation(context))
        .into((ImageView) findViewById(R.id.image));

Crop

Color

Blur

Mask(掩模)

GPU Filter(滤镜)

上一篇 下一篇

猜你喜欢

热点阅读