当前位置:网站首页>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
边栏推荐
- Fidde breakpoint interception
- Dragon Boat Festival wellbeing, use blessing words to generate word cloud
- Analysis of 43 cases of MATLAB neural network: Chapter 11 optimization of continuous Hopfield Neural Network -- optimization calculation of traveling salesman problem
- Echart line chart: different colors are displayed when the names of multiple line charts are the same
- Local file search tool everything
- Time complexity and space complexity
- Detailed explanation of the player startup process of ijkplayer code walkthrough 2
- The jadx decompiler can decompile jars and apks
- Echart histogram: stacked histogram displays value
- 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
猜你喜欢
![[DP 01 backpack]](/img/be/1e5295684ead652eebfb72ab0be47a.jpg)
[DP 01 backpack]

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

RN Metro packaging process and sentry code monitoring

pthon 执行 pip 指令报错 You should consider upgrading via ...

JetPack - - - DataBinding

【新手上路常见问答】关于技术管理

二分查找
![[one · data 𞓜 simple implementation of the leading two-way circular linked list]](/img/a2/08f55012cd815190db76237f013961.png)
[one · data 𞓜 simple implementation of the leading two-way circular linked list]

Fichier local second Search Tool everything

【Kernel】驱动编译的两种方式:编译成模块、编译进内核(使用杂项设备驱动模板)
随机推荐
Time complexity and space complexity
【新手上路常见问答】关于技术管理
Detailed explanation of scrcpy client code walk through H264 raw stream decoding process
Logcat -b events and eventlogtags print the location correspondence of the events log in the code
Applet Use of spaces
Using the shutter floor database framework
[var const let differences]
楊輝三角形詳解
1+1 > 2, share creators can help you achieve
Echart histogram: echart implements stacked histogram
ADB shell CMD overlay debugging command facilitates viewing system framework character resource values
本地文件秒搜工具 Everything
Analysis of synchronized
Scrcpy development environment construction and source code reading
MFS details (VII) -- MFS client and web monitoring installation configuration
JS to realize bidirectional data binding
Uni app disable native navigation bar
Ijkplayer compilation process record
Applet disable native top
Wechat applet development (requesting background data and encapsulating request function)