当前位置:网站首页>Glide usage notes
Glide usage notes
2022-06-13 06:34:00 【Sindyue】
1. obtain bitmap , And set it on the component
Glide.with(mContext).load(url).asBitmap().into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
image.setImageBitmap(resource);
}
}); // Set in method asBitmap You can set the callback type
2. Load normal pictures
Glide.with(context)
.load(imageURL)
.placeholder(R.drawable.default_iv)
.centerCrop()
.transform(new GlideRoundTransform(context, roundCornerDp))
.into(holder.imageView);
3. Image tool class with rounded corners
public class GlideRoundTransform extends BitmapTransformation {
private static float radius = 0f;
public GlideRoundTransform(Context context) {
this(context, 4);
}
public GlideRoundTransform(Context context, int dp) {
super(context);
this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return roundCrop(pool, toTransform);
}
private static Bitmap roundCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
canvas.drawRoundRect(rectF, radius, radius, paint);
return result;
}
@Override
public String getId() {
return getClass().getName() + Math.round(radius);
}
}
4. load https Related graphs
glide Use your own network request to load pictures , Want to use glide visit https picture , Must be replaced glide The original method of loading pictures , Make it trust all certificates as well .
With OkHttpClient Request as an example , The following classes and related configurations are required :
4.1 OkHttpGlideModule.class
import android.content.Context;
import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.module.GlideModule;
import java.io.InputStream;
import okhttp3.OkHttpClient;
public class OkHttpGlideModule implements GlideModule {
@Override
public void applyOptions(Context context, GlideBuilder builder) {
}
@Override
public void registerComponents(Context context, Glide glide) {
OkHttpClient mHttpClient = new OkHttpClient().newBuilder()
.sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
.hostnameVerifier(SSLSocketClient.getHostnameVerifier())
.build();
glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(mHttpClient));
}
}
4.2 OkHttpGlideModule.class
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.util.ContentLengthInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class OkHttpStreamFetcher implements DataFetcher<InputStream> {
private final OkHttpClient client;
private final GlideUrl url;
private InputStream stream;
private ResponseBody responseBody;
public OkHttpStreamFetcher(OkHttpClient client, GlideUrl url) {
this.client = client;
this.url = url;
}
@Override
public InputStream loadData(Priority priority) throws Exception {
Request.Builder requestBuilder = new Request.Builder()
.url(url.toStringUrl());
for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
String key = headerEntry.getKey();
requestBuilder.addHeader(key, headerEntry.getValue());
}
Request request = requestBuilder.build();
Response response = client.newCall(request).execute();
responseBody = response.body();
if (!response.isSuccessful()) {
throw new IOException("Request failed with code: " + response.code());
}
long contentLength = responseBody.contentLength();
stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
return stream;
}
@Override
public void cleanup() {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
if (responseBody != null) {
responseBody.close();
}
}
@Override
public String getId() {
return url.getCacheKey();
}
@Override
public void cancel() {
}
}
4.3 OkHttpUrlLoader.class
import android.content.Context;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.GenericLoaderFactory;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;
import java.io.InputStream;
import okhttp3.OkHttpClient;
public class OkHttpUrlLoader implements ModelLoader<GlideUrl, InputStream> {
public static class Factory implements ModelLoaderFactory<GlideUrl, InputStream> {
private static volatile OkHttpClient internalClient;
private OkHttpClient client;
private static OkHttpClient getInternalClient() {
if (internalClient == null) {
synchronized (Factory.class) {
if (internalClient == null) {
internalClient = new OkHttpClient();
}
}
}
return internalClient;
}
public Factory() {
this(getInternalClient());
}
public Factory(OkHttpClient client) {
this.client = client;
}
@Override
public ModelLoader<GlideUrl, InputStream> build(Context context, GenericLoaderFactory factories) {
return new OkHttpUrlLoader(client);
}
@Override
public void teardown() {
}
}
private final OkHttpClient client;
public OkHttpUrlLoader(OkHttpClient client) {
this.client = client;
}
@Override
public DataFetcher<InputStream> getResourceFetcher(GlideUrl model, int width, int height) {
return new OkHttpStreamFetcher(client, model);
}
}
4.4 SSLSocketClient.class
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class SSLSocketClient {
// Access to this SSLSocketFactory
public static SSLSocketFactory getSSLSocketFactory() {
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, getTrustManager(), new SecureRandom());
return sslContext.getSocketFactory();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// obtain TrustManager
private static TrustManager[] getTrustManager() {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
};
return trustAllCerts;
}
// obtain HostnameVerifier
public static HostnameVerifier getHostnameVerifier() {
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
return hostnameVerifier;
}
}
4.5 Configuration and use GlideModule
stay AndroidManifest in application The label states that GlideMoudle, Note that the circled part must indicate the full path , Unavailable . Instead of .
Be careful : stay OkHttpGlideModule As you can see in, we have rebuilt a okhttp And registered to glide in :
Reference link :https://blog.csdn.net/u014752325/article/details/73217577
边栏推荐
- MFS explanation (V) -- MFS metadata log server installation and configuration
- Explication détaillée du triangle Yang hui
- JS to realize bidirectional data binding
- Wechat applet development (requesting background data and encapsulating request function)
- ‘ipconfig‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件。
- Wechat applet (get location)
- 【新手上路常见问答】关于技术管理
- Kotlin foundation extension
- 线程相关点
- The jadx decompiler can decompile jars and apks
猜你喜欢
Relationship between fragment lifecycle and activity
Echart histogram: echart implements stacked histogram
c语言对文件相关的处理和应用
[kernel] two methods of driver compilation: compiling into modules and compiling into the kernel (using miscellaneous device driver templates)
[solution] camunda deployment process should point to a running platform rest API
[2022 college entrance examination season] what I want to say as a passer-by
Analysis of 43 cases of MATLAB neural network: Chapter 10 classification of discrete Hopfield Neural Network -- evaluation of scientific research ability of colleges and Universities
端午安康,使用祝福话语生成词云吧
‘ipconfig‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件。
Recommend a capacity expansion tool to completely solve the problem of insufficient disk space in Disk C and other disks
随机推荐
端午安康,使用祝福话语生成词云吧
Huawei developer certification and deveco studio compiler Download
Kotlin basic string operation, numeric type conversion and standard library functions
MFS details (vii) - - MFS client and Web Monitoring installation configuration
The web server failed to start Port 7001 was already in use
JS to realize bidirectional data binding
The boys x pubgmobile linkage is coming! Check out the latest game posters
Logcat -b events and eventlogtags print the location correspondence of the events log in the code
二分查找
Wechat applet (pull-down refresh data) novice to
IOError(Errors.E050.format(name=name))
Kotlin collaboration channel
1+1 > 2, share creators can help you achieve
[MySQL] basic knowledge review
Common websites and tools
Regular verification of mobile phone number, landline email ID card
PHP redis makes high burst spike
Custom view
SSM框架整合--->简单后台管理
The processing and application of C language to documents