Glide — Dynamically Use Model Loaders


自定义图像大小

提示:如果你还没读过我们之前的博客,现在去读一下。否则,下面这部分看起来很困难。

作为一个简短的回顾:通常 Glide 的请求是和 GlideUrl 类来使用的。上周我们已经向你展示了如何创建一个新的接口,来考虑增加宽度和高度。

public interface CustomImageSizeModel {  
String requestCustomSizeUrl(int width, int height);
}

我们创建了一个实现,它及案例额传递了图像的 URL 加上尺寸提交给了工作服务器。

public static class CustomImageSizeModelFutureStudio implements CustomImageSizeModel {
    String baseImageUrl;
    public CustomImageSizeModelFutureStudio(String baseImageUrl) {
this.baseImageUrl = baseImageUrl;
}
    @Override
public String requestCustomSizeUrl(int width, int height) {
return baseImageUrl + "?w=" + width + "&h=" + height;
}
}

最后,这并不是最重要的,我们必须创建一个 CustomImageSizeUrlLoader,它传了宽度和高度给了我们的 model 实现:

public static class CustomImageSizeUrlLoader extends BaseGlideUrlLoader<CustomImageSizeModel> {  
public CustomImageSizeUrlLoader(Context context) {
super( context );
}
    @Override
protected String getUrl(CustomImageSizeModel model, int width, int height) {
return model.requestCustomSizeUrl( width, height );
}
}

Model Loader 和 .using() 的动态使用

目前我们已经声明了 Glide module。Glide 会把它用在每一个请求。如果你不想这样,从AndroidManifest.xml 中删除你的 Glide module。我们可以这么做是因为 Glide 提供了.using() 方法去为单个的请求指定一个 model。

String baseImageUrl = "https://futurestud.io/images/example.png";  
CustomImageSizeModel customImageRequest = new CustomImageSizeModelFutureStudio( baseImageUrl );
Glide  
.with( context )
.using( new CustomImageSizeUrlLoader( context ) )
.load( customImageRequest )
.into( imageView1 );

正如你看到的,我们正在创建一个 CustomImageSizeModelFutureStudio 对象来为我们的图像按照指定的大小加载。因为没有在 Glide module 中声明 CustomImageSizeModel 接口,我们必须指明这行代码 .using(new CustomImageSizeUrlLoader(context))。Glide 现在会只为这个请求用这个 model。对于其他的请求,即使它们有 CustomImageSizeModel 接口,也不会受影响。