Glide4.7.1的使用
阿新 • • 發佈:2018-12-13
1.配置
1.1.新建一個MyAppGlideModule繼承AppGlideModule,建議使用官方使用的方法,方便後續需求而進行拓展配置
@GlideModule public class MyAppGlideModule extends AppGlideModule { @Override public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) { //下面3中設定都可自定義大小,以及完全自定義實現 //記憶體緩衝 MemorySizeCalculator calculator = new MemorySizeCalculator.Builder(context) .setMemoryCacheScreens(2) .setBitmapPoolScreens(3) .build(); builder.setMemoryCache(new LruResourceCache(calculator.getMemoryCacheSize())); //Bitmap 池 builder.setBitmapPool(new LruBitmapPool(calculator.getBitmapPoolSize())); //磁碟快取 int diskCacheSizeBytes = 1024 * 1024 * 100; //100 MB builder.setDiskCache(new InternalCacheDiskCacheFactory(context, diskCacheSizeBytes)); } }
1.2.新建一個封裝類GlideUtil,方便以後得維護。目前沒有進行很好的封裝,方便自己的需求新增,可以根據自己的需要進行修改
/** * 建立日期:2018/11/23 on 10:38 * 描述: glide工具類 */ public class GlideUtil { private static GlideUtil instance; RequestOptions options; Context mContext; private GlideUtil(Context context){ options = new RequestOptions(); options.skipMemoryCache(false); options.diskCacheStrategy(DiskCacheStrategy.ALL); options.priority(Priority.HIGH); options.error(R.mipmap.home_img_loading_pic1); //設定佔位符,預設 options.placeholder(R.mipmap.home_img_loading_pic1); //設定錯誤符,預設 options.error(R.mipmap.home_img_loading_pic1); mContext=context; } public static GlideUtil getInstance(Context context){ if (instance==null){ synchronized (GlideUtil.class){ if (instance==null){ instance=new GlideUtil(context); } } } return instance; } //設定佔位符 public void setPlaceholder(int id){ options.placeholder(id); } public void setPlaceholder(Drawable drawable){ options.placeholder(drawable); } //設定錯誤符 public void setError(int id){ options.error(id); } public void setError(Drawable drawable){ options.error(drawable); } public void showImage(String url, ImageView imageView){ GlideApp.with(mContext) .load(url) .apply(options) .into(imageView); } //以圖片寬度為基準 public void showImageWidthRatio(String url, final ImageView imageView, final int width){ GlideApp.with(mContext) .asBitmap() .apply(options) .load(url) .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { int imageWidth=resource.getWidth(); int imageHeight=resource.getHeight(); int height = width * imageHeight / imageWidth; ViewGroup.LayoutParams params=imageView.getLayoutParams(); params.height=height; params.width=width; imageView.setImageBitmap(resource); } }); } //以圖片高度為基準 public void showImageHeightRatio(String url, final ImageView imageView, final int height){ GlideApp.with(mContext) .asBitmap() .apply(options) .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { int imageWidth=resource.getWidth(); int imageHeight=resource.getHeight(); int width = height * imageHeight / imageWidth; ViewGroup.LayoutParams params=imageView.getLayoutParams(); params.height=height; params.width=width; imageView.setImageBitmap(resource); } }); } //設定圖片固定的大小尺寸 public void showImageWH(String url, final ImageView imageView, int height,int width){ options.override(width,height); GlideApp.with(mContext) .load(url) .apply(options) .into(imageView); } //設定圖片圓角,以及弧度 public void showImageRound(String url, final ImageView imageView,int radius){ options.transform(new CornersTranform(radius)); // options.transform(new GlideCircleTransform()); GlideApp.with(mContext) .load(url) .apply(options) .into(imageView); } public void showImageRound(String url, final ImageView imageView,int radius, int height,int width){ //不一定有效,當原始圖片為長方形時設定無效 options.override(width,height); options.transform(new CornersTranform(radius)); // options.centerCrop(); //不能與圓角共存 GlideApp.with(mContext) .load(url) .apply(options) .into(imageView); } public void showImageRound(String url, final ImageView imageView){ //自帶圓角方法,顯示圓形 options.circleCrop(); GlideApp.with(mContext) .load(url) .apply(options) .into(imageView); } }
1.3使用方式
GlideUtil.getInstance(context).showImageRound(aNew.getImages_urls().get(0),vh.img_news_pic1);
2.特殊需求,以及注意事項
2.1擋我們需要給圖片使用圓角的時候我們需要進行一些處理。
有兩種方式:
a.可以根據Glide提供擴充套件介面自己實現方法(4.0之前和之後的版本的實現方式有點不一樣)
/** * glide處理圓角圖片\ */ public class CornersTranform extends BitmapTransformation { private float radius; public CornersTranform() { super(); radius = 10; } public CornersTranform(float radius) { super(); this.radius = radius; } @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { return cornersCrop(pool, toTransform); } private Bitmap cornersCrop(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.isRecycled()){ result.recycle(); result = null; } 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 void updateDiskCacheKey(MessageDigest messageDigest) { } }
實現方法
public void showImageRound(String url, final ImageView imageView,int radius, int height,int width){
//不一定有效,當原始圖片為長方形時設定無效
options.override(width,height);
options.transform(new CornersTranform(radius));
// options.centerCrop(); //不能與圓角共存
GlideApp.with(mContext)
.load(url)
.apply(options)
.into(imageView);
}
上面的方式可以自定義圓角弧度的,注意不能options.centerCrop();一起使用,因為一起使用會讓圓角失效(原因網上已經有解釋以及實現共存方式)
glide官方還提供了 options.circleCrop();方法這是實現圓形的圖片
//自帶圓角方法,顯示圓形
options.circleCrop();
GlideApp.with(mContext)
.load(url)
.apply(options)
.into(imageView);
b.上面的方式個人感覺不是太友好,我採取的是自定義一個實現圓角的控制元件
RoundImageView實現圓角弧度,實現和使用簡單,但不能隨意修改
/**
* 建立日期:2018/10/19 on 15:38
* 描述: 自定義圓角圖片
*/
public class RoundImageView extends AppCompatImageView {
//圓角大小,預設為10
private int mBorderRadius = 10;
private Paint mPaint;
// 3x3 矩陣,主要用於縮小放大
private Matrix mMatrix;
//渲染影象,使用影象為繪製圖形著色
private BitmapShader mBitmapShader;
public RoundImageView(Context context) {
this(context, null);
}
public RoundImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mMatrix = new Matrix();
mPaint = new Paint();
mPaint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
if (getDrawable() == null){
return;
}
Bitmap bitmap = drawableToBitamp(getDrawable());
mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
float scale = 1.0f;
if (!(bitmap.getWidth() == getWidth() && bitmap.getHeight() == getHeight()))
{
// 如果圖片的寬或者高與view的寬高不匹配,計算出需要縮放的比例;縮放後的圖片的寬高,一定要大於我們view的寬高;所以我們這裡取大值;
scale = Math.max(getWidth() * 1.0f / bitmap.getWidth(),
getHeight() * 1.0f / bitmap.getHeight());
}
// shader的變換矩陣,我們這裡主要用於放大或者縮小
mMatrix.setScale(scale, scale);
// 設定變換矩陣
mBitmapShader.setLocalMatrix(mMatrix);
// 設定shader
mPaint.setShader(mBitmapShader);
canvas.drawRoundRect(new RectF(0,0,getWidth(),getHeight()), mBorderRadius, mBorderRadius,
mPaint);
}
private Bitmap drawableToBitamp(Drawable drawable)
{
if (drawable instanceof BitmapDrawable)
{
BitmapDrawable bd = (BitmapDrawable) drawable;
return bd.getBitmap();
}
// 當設定不為圖片,為顏色時,獲取的drawable寬高會有問題,所有當為顏色時候獲取控制元件的寬高
int w = drawable.getIntrinsicWidth() <= 0 ? getWidth() : drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight() <= 0 ? getHeight() : drawable.getIntrinsicHeight();
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
drawable.draw(canvas);
return bitmap;
}
}
//使用:在對應的佈局檔案中使用
<com.bestapp.myglidedemo.image.RoundImageView
android:id="@+id/img_news_pic1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/news_type_bottom"
android:scaleType="centerCrop"
android:src="@mipmap/home_img_loading_pic1" />
CustomRoundAngleImageView實現比較複雜,但是可以單獨隨意定義4個角的弧度
/**
* 建立日期:2018/10/22 on 11:24
*/
public class CustomRoundAngleImageView extends AppCompatImageView {
float width, height;
public CustomRoundAngleImageView(Context context) {
this(context, null);
init(context, null);
}
public CustomRoundAngleImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
init(context, attrs);
}
public CustomRoundAngleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private int defaultRadius = 0;
private int radius;
private int leftTopRadius;
private int rightTopRadius;
private int rightBottomRadius;
private int leftBottomRadius;
private void init(Context context, AttributeSet attrs) {
if (Build.VERSION.SDK_INT < 18) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
// 讀取配置
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.Custom_Round_Image_View);
radius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_radius, defaultRadius);
leftTopRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_left_top_radius, defaultRadius);
rightTopRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_right_top_radius, defaultRadius);
rightBottomRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_right_bottom_radius, defaultRadius);
leftBottomRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_left_bottom_radius, defaultRadius);
//如果四個角的值沒有設定,那麼就使用通用的radius的值。
if (defaultRadius == leftTopRadius) {
leftTopRadius = radius;
}
if (defaultRadius == rightTopRadius) {
rightTopRadius = radius;
}
if (defaultRadius == rightBottomRadius) {
rightBottomRadius = radius;
}
if (defaultRadius == leftBottomRadius) {
leftBottomRadius = radius;
}
array.recycle();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
width = getWidth();
height = getHeight();
}
@Override
protected void onDraw(Canvas canvas) {
//這裡做下判斷,只有圖片的寬高大於設定的圓角距離的時候才進行裁剪
int maxLeft = Math.max(leftTopRadius, leftBottomRadius);
int maxRight = Math.max(rightTopRadius, rightBottomRadius);
int minWidth = maxLeft + maxRight;
int maxTop = Math.max(leftTopRadius, rightTopRadius);
int maxBottom = Math.max(leftBottomRadius, rightBottomRadius);
int minHeight = maxTop + maxBottom;
if (width >= minWidth && height > minHeight) {
Path path = new Path();
//四個角:右上,右下,左下,左上
path.moveTo(leftTopRadius, 0);
path.lineTo(width - rightTopRadius, 0);
path.quadTo(width, 0, width, rightTopRadius);
path.lineTo(width, height - rightBottomRadius);
path.quadTo(width, height, width - rightBottomRadius, height);
path.lineTo(leftBottomRadius, height);
path.quadTo(0, height, 0, height - leftBottomRadius);
path.lineTo(0, leftTopRadius);
path.quadTo(0, 0, leftTopRadius, 0);
canvas.clipPath(path);
}
super.onDraw(canvas);
}
}
新建一個資原始檔attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Custom_Round_Image_View">
<attr name="radius" format="dimension"/>
<attr name="left_top_radius" format="dimension"/>
<attr name="right_top_radius" format="dimension"/>
<attr name="right_bottom_radius" format="dimension"/>
<attr name="left_bottom_radius" format="dimension"/>
</declare-styleable>
</resources>
使用
<com.bestapp.myglidedemo.image.CustomRoundAngleImageView
android:id="@+id/img_type3_pic1"
android:layout_width="200px"
android:layout_height="200px"
android:scaleType="centerCrop"
app:left_top_radius="10px"
app:left_bottom_radius="10px"
android:src="@mipmap/home_img_loading_pic1" />
注意:com.bestapp.myglidedemo.image.是自己檔案所在的路徑,根據自己的情況修改
2.2設定圖片寬高
2.2.1 根據寬度為基準設定圖片寬高
//以圖片寬度為基準
public void showImageWidthRatio(String url, final ImageView imageView, final int width){
GlideApp.with(mContext)
.asBitmap()
.apply(options)
.load(url)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
int imageWidth=resource.getWidth();
int imageHeight=resource.getHeight();
int height = width * imageHeight / imageWidth;
ViewGroup.LayoutParams params=imageView.getLayoutParams();
params.height=height;
params.width=width;
imageView.setImageBitmap(resource);
}
});
}
2.2.2根據高度為基準設定圖片寬高
//以圖片高度為基準
public void showImageHeightRatio(String url, final ImageView imageView, final int height){
GlideApp.with(mContext)
.asBitmap()
.apply(options)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
int imageWidth=resource.getWidth();
int imageHeight=resource.getHeight();
int width = height * imageHeight / imageWidth;
ViewGroup.LayoutParams params=imageView.getLayoutParams();
params.height=height;
params.width=width;
imageView.setImageBitmap(resource);
}
});
}
2.2.3單獨設定寬高使用options.override(width,height);方法
總結:基本可以概括了一般的使用,當然還有更高階的使用還沒有涉及到。本文是根據本人自己的專案情況遇到的問題來寫的,當然同時借鑑了網上的東西,有什麼不對的希望指出。