Android使用Glide加载View背景图片

一般常用Glide加载图片到ImageView上,如何加载到View及Layout的背景上呢?

Glide 4 及以上

1
2
3
4
5
6
7
8
9
10
11
public static void loadViewBackground(String url, final View view) {
SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, Transition<? super Drawable> transition) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.setBackground(resource);
}
}
};
GlideApp.with(view.getContext()).load(url).into(simpleTarget);
}

常用方式

第一种方式:

1
2
3
4
5
6
7
8
9
10
11
12
Glide.with(context)
.load(url)
.asBitmap()
.into(new SimpleTarget<Bitmap>(180, 180) { //图片宽高
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
Drawable drawable = new BitmapDrawable(resource);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
layout.setBackground(drawable); //设置背景
}
}
});

该方式按照设置的宽高去截取图片,再去加载到控件背景上,有时会导致图片显示不全

第二种方式:

1
2
3
4
5
6
7
8
Glide.with(context)
.load(url)
.into(new ViewTarget<View, GlideDrawable>(layout) { //括号里为需要加载的控件
@Override
public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
this.view.setBackground(resource.getCurrent());
}
});

该方式则完美加载图片

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :