Android開發第三方庫glide和圓形控制元件circleimageview一起使用第一次進入無法顯示問題
阿新 • • 發佈:2018-12-30
在使用glide載入圓形頭像,圓形頭像使用控制元件circleimageview,發現第一進入頭像根本不會顯示,後來使用android v4包提供的RoundedBitmapDrawableFactory完美的解決了這個問題,在使用RoundedBitmapDrawableFactory時,xml中的控制元件直接可以使用控制元件imageview.
在使用RoundedBitmapDrawableFactory時,設定RoundedBitmapDrawableFactory使其帶有白色邊框,以及從中間裁剪,避免原形圖片圓形圖片放大的問題,若是不需要帶白色邊框直接可以傳入false,需要顯示白色邊框傳入true.實現如下:
public class ImageUtils {
public static void loadHeadImage(final Context context, String url, final ImageView photo, final boolean isBord) {
Glide.with(context).load(url).asBitmap().centerCrop().into(new BitmapImageViewTarget(photo) {
@Override
protected void setResource (Bitmap resource) {
if (isBord==true){
Drawable image = setRoundImageWithBorder(context, resource);
photo.setImageDrawable(image);
}else {
RoundedBitmapDrawable drawable = setNoBordRoundImageWithBorder(context,resource);
photo.setImageDrawable(drawable);
}
}
});
}
/**
* 設定RoundedBitmapDrawableFactory
* 其方法:
* setCircular 是否是圓形
* setAlpha 透明度
* setAntiAlias抗鋸齒
* setDither 防抖動
*
* @param context
* @param bitmap
* @return
*/
private static Drawable setRoundImageWithBorder(Context context, Bitmap bitmap) {
//獲取原圖寬高
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
//邊框寬度 pixel設定20畫素
int borderWidthHalf = 20;
int bitmapSquareWidth = Math.min(bitmapWidth, bitmapHeight);
int newBitmapSquareWidth = bitmapSquareWidth + borderWidthHalf;
Bitmap roundedBitmap = Bitmap.createBitmap(newBitmapSquareWidth, newBitmapSquareWidth, Bitmap.Config.ARGB_8888);
//裁剪後圖像, X,Y除以2進行一箇中心裁剪
Canvas canvas = new Canvas(roundedBitmap);
int x = borderWidthHalf + bitmapSquareWidth - bitmapWidth;
int y = borderWidthHalf + bitmapSquareWidth - bitmapHeight;
canvas.drawBitmap(bitmap, x / 2, y / 2, null);
//新增圖片邊框
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(borderWidthHalf);
paint.setColor(Color.WHITE); //設定邊框為白色
canvas.drawCircle(canvas.getWidth() / 2, canvas.getWidth() / 2, newBitmapSquareWidth / 2, paint);
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), roundedBitmap);
roundedBitmapDrawable.setGravity(Gravity.CENTER);
roundedBitmapDrawable.setCircular(true); //設定為原形圖片
return roundedBitmapDrawable;
}
/**
* 不包含白色邊框
* @param context
* @return
*/
private static RoundedBitmapDrawable setNoBordRoundImageWithBorder(Context context,Bitmap bitmap){
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), bitmap);
roundedBitmapDrawable.setCircular(true); //設定為原形圖片
return roundedBitmapDrawable;
}
}