圓角圖片2 RoundedBitmapDrawable 加載本地圖片

  • 參考博文

  1. Android 圓角圖片的實現         ——矩形圖片通過裁剪實現圓形圖片
  2. Android圓角圖片和圓形圖片實現總結   ——多種圓角圖片繪製方式

  3. android RoundedBitmapDrawable最簡單方式實現圓角圖片   ——RounedBitMapDrawable圖片顯示變形問題處理以及添加邊框

 

  • 效果演示(引用其他博文效果,實測如下)

  

  • 核心代碼

⭐矩形圖片 ivRectImg.setImageDrawable(bitmapDrawable);

public static RoundedBitmapDrawable tranRoundBitmap(Context context,int drawableId) {
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),drawableId);
        RoundedBitmapDrawable bitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), bitmap);
        bitmapDrawable.setAntiAlias(true);
        bitmapDrawable.setCornerRadius(10); //控制圓角半徑
//        ivRectImg.setImageDrawable(bitmapDrawable); //使用方法
        return bitmapDrawable;
}

 

圓形圖片 Bitmap.createBitmap 變形圖片的處理

private void circleBitmap() {
     Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.image_bg);
        Bitmap circle = null;
        int min = Math.min(width, height);
        int max = Math.max(width, height);
        if (width == height) {
            circle = Bitmap.createBitmap(bitmap, 0, 0, width, height);
        } else {
            // 居中裁剪
            if (width > height) {
                circle = Bitmap.createBitmap(bitmap, (max - min) / 2, 0, min, min);
            } else {
                circle = Bitmap.createBitmap(bitmap, 0, (max - min) / 2, min, min);
            }
        }
        RoundedBitmapDrawable bitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), circle);
        bitmapDrawable.setCornerRadius(min / 2);
        bitmapDrawable.setAntiAlias(true);
        ivCircleImg.setImageDrawable(bitmapDrawable);
    }

 

圓形圖片添加邊框 drawCircle (圓角矩形不統用)

        Canvas canvas = new Canvas(roundedBitmap);
        Paint borderPaint = new Paint();
        borderPaint.setStyle(Paint.Style.STROKE);
        borderPaint.setStrokeWidth(borderWidthHalf);
        borderPaint.setColor(Color.WHITE);
        //添加邊框
        canvas.drawCircle(canvas.getWidth()/2, canvas.getWidth()/2, newBitmapSquareWidth/2, borderPaint);    

 

  • 與GlideApp對比

  如果Android項目中僅少的使用圓角圖片且無需加載網絡圖片,此方法更爲簡單合適,不需要添加依賴以及很多的代碼。GlideApp加載網絡圖片較爲方便,以及一些內存緩存的機制。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章