自定义图片大小
提示:如果你没有读之前的文章,确保你看了。否则下面内容会让你困惑。
作个快速回顾:通常Glide请求是从GlideUrl类中生成。上篇文章,我们展示了如何创建一个新的接口,额外将宽度和高度添加到考虑范围:
public interface CustomImageSizeModel {
String requestCustomSizeUrl(int width, int height);
}
我们创建了它的一个实例,向我们的Future Studio服务器传递了额外尺寸图片的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 Loaders的.using()的动态使用
目前为止,我们上面的代码声明的Glide module。Glide会为每个单独的请求使用它。如果你不希望那样,通过在AndroidManifest.xml
里移除来关闭你的Glide module。我们可以那样做,是因为Glide提供了.using()
方法为一个单独请求去指定一个模型:
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会只为这个请求使用这个模型。其他的所有请求,即使他们也从CustomImageSizeModel实例构建,也不生效。