使用 RoundedBitmapDrawable 建立圓角頭像詳解

極速24號發表於2019-04-02

1. 什麼是 RoundedBitmapDrawable,它存在的意義是什麼?

RoundedBitmapDrawable 是 Android 版本 22.1.0 的時候加入的,它的主要作用是建立圓角的 Drawable。

A Drawable that wraps a bitmap and can be drawn with rounded corners.

Google 新增此類的原因可能是彌補 Android API 中沒有直接支援建立圓角 Drawable 的空缺吧。

2. 怎麼用?

RoundedBitmapDrawable 不僅可以建立圓角的 Drawable,還可以建立圓角矩形的 Drawable,接下來,我們就針對這兩種情況分別討論。

2.1 圓形 Drawable

2.1.1 概述

建立和應用 RoundedBitmapDrawable 一共分三步:

  1. 建立 RoundedBitmapDrawable 物件;
  2. 設定 RoundedBitmapDrawable 為圓形;
  3. 將 RoundedBitmapDrawable 設定到 ImageView 上。
2.1.2 詳述
  1. 建立 RoundedBitmapDrawable 物件
RoundedBitmapDrawable circleDrawable = RoundedBitmapDrawableFactory.create(@NonNull Resources res, @Nullable Bitmap bitmap);
複製程式碼
  1. 設定 RoundedBitmapDrawable 為圓形
RoundedBitmapDrawable.setCircular(boolean circular);
複製程式碼
  1. 將 RoundedBitmapDrawable 設定到 ImageView 上
ImageView.setImageDrawable(@Nullable Drawable drawable);
複製程式碼
2.1.3 應用例項
//1. 資原始檔

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".roundedbitmapdrawabletutorial.RoundedBitmapDrawableTutorialActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/rounded_bitmap_drawable_circle_fit_center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/padding_small"
            android:background="@color/white"
            android:scaleType="fitCenter"
            android:src="@drawable/tiger" />

    </LinearLayout>
</ScrollView>
複製程式碼
//2. Activity

public class RoundedBitmapDrawableTutorialActivity extends AppCompatActivity {

    private int mScreenWidth, mScreenHeight, mViewWidth, mViewHeight;
    private ImageView mCircleFitCenterView;
    private LinearLayout.LayoutParams mCircleLayoutParams;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rounded_bitmap_drawable_tutorial);
        getScreenProperty();
        initView();
        initData();
    }

    private void getScreenProperty(){
        mScreenWidth = DisplayMetricsUtil.getScreenWidth(this);
        mScreenHeight = DisplayMetricsUtil.getScreenHeight(this);
        mViewWidth = mScreenWidth * 2/3;
        mViewHeight = mScreenHeight * 2/3;
    }

    private void initView(){
        mCircleFitCenterView = findViewById(R.id.rounded_bitmap_drawable_circle_fit_center);
        mCircleLayoutParams = new LinearLayout.LayoutParams(mViewWidth, mViewWidth);
        mCircleLayoutParams.topMargin = (int)getResources().getDimension(R.dimen.padding_small);
        mCircleFitCenterView.setLayoutParams(mCircleLayoutParams);
    }

    private void initData(){
        //第一步
        RoundedBitmapDrawable circleDrawable = RoundedBitmapDrawableFactory.create(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.tiger));
        //第二步
        circleDrawable.setCircular(true);
        //第三步
        mCircleFitCenterView.setImageDrawable(circleDrawable);
    }

}
複製程式碼

最終效果如下:

使用 RoundedBitmapDrawable 建立圓角頭像詳解

2.2 圓角矩形 Drawable

2.2.1 概述

建立和應用 RoundedBitmapDrawable 一共分三步:

  1. 建立 RoundedBitmapDrawable 物件;
  2. 為 RoundedBitmapDrawable 設定圓角的半徑;
  3. 將 RoundedBitmapDrawable 設定到 ImageView 上。
2.2.2 詳述
  1. 建立 RoundedBitmapDrawable 物件
RoundedBitmapDrawable circleDrawable = RoundedBitmapDrawableFactory.create(@NonNull Resources res, @Nullable Bitmap bitmap);
複製程式碼
  1. 為 RoundedBitmapDrawable 設定圓角的半徑
RoundedBitmapDrawable.setCornerRadius(float cornerRadius);
複製程式碼
  1. 將 RoundedBitmapDrawable 設定到 ImageView 上
ImageView.setImageDrawable(@Nullable Drawable drawable);
複製程式碼
2.2.3 應用例項
//1. 資原始檔

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".roundedbitmapdrawabletutorial.RoundedBitmapDrawableTutorialActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/rounded_bitmap_drawable_round_rectangle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/padding_small"
            android:background="@color/white"
            android:scaleType="fitCenter"
            android:src="@drawable/tiger" />

    </LinearLayout>
</ScrollView>
複製程式碼
//2. Activity
public class RoundedBitmapDrawableTutorialActivity extends AppCompatActivity {

    private int mScreenWidth, mScreenHeight, mViewWidth, mViewHeight;
    private ImageView mRoundRectangleView;
    private LinearLayout.LayoutParams mRoundRectangleLayoutParams;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rounded_bitmap_drawable_tutorial);
        getScreenProperty();
        initView();
        initData();
    }

    private void getScreenProperty(){
        mScreenWidth = DisplayMetricsUtil.getScreenWidth(this);
        mScreenHeight = DisplayMetricsUtil.getScreenHeight(this);
        mViewWidth = mScreenWidth * 2/3;
        mViewHeight = mScreenHeight * 2/3;
    }

    private void initView(){
        mRoundRectangleView = findViewById(R.id.rounded_bitmap_drawable_round_rectangle);
        mRoundRectangleLayoutParams = new LinearLayout.LayoutParams(mViewWidth, mViewHeight);
        mRoundRectangleLayoutParams.topMargin = (int)getResources().getDimension(R.dimen.padding_small);
        mRoundRectangleView.setLayoutParams(mRoundRectangleLayoutParams);
    }

    private void initData(){
        //第一步
        RoundedBitmapDrawable roundRectangleDrawable = RoundedBitmapDrawableFactory.create(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.tiger));
        //第二步
        roundRectangleDrawable.setCornerRadius((mViewWidth < mViewHeight ? mViewWidth : mViewHeight)/32);
        //第三步
        mRoundRectangleView.setImageDrawable(roundRectangleDrawable);
    }

}
複製程式碼

最終效果如下:

使用 RoundedBitmapDrawable 建立圓角頭像詳解

只需要對 RoundedBitmapDrawable 的圓角的半徑稍作修改,就可以的得到如下效果:

使用 RoundedBitmapDrawable 建立圓角頭像詳解

修改方法如下:

//第一步
RoundedBitmapDrawable roundRectangleDrawable = RoundedBitmapDrawableFactory.create(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.tiger));
//第二步
roundRectangleDrawable.setCornerRadius((mViewWidth < mViewHeight ? mViewWidth : mViewHeight)/2));
//第三步
mRoundRectangleView.setImageDrawable(roundRectangleDrawable);
複製程式碼

是不是很好用?

3. RoundedBitmapDrawable 實現原理是什麼?

知道了怎麼用 RoundedBitmapDrawable 之後,讓我們一塊看下,RoundedBitmapDrawable 到底是如何“變圓”的。

  1. 進入 RoundedBitmapDrawableFactory 類的 create(@NonNull Resources res, @Nullable Bitmap bitmap) 方法:
public static RoundedBitmapDrawable create(@NonNull Resources res, @Nullable Bitmap bitmap) {
    return (RoundedBitmapDrawable)(VERSION.SDK_INT >= 21 ? new RoundedBitmapDrawable21(res, bitmap) : new RoundedBitmapDrawableFactory.DefaultRoundedBitmapDrawable(res, bitmap));
}
複製程式碼

在這裡我們只研究 VERSION.SDK_INT 小於 21 的情況,另外一種情況,大家自己去分析吧。

  1. 進入 RoundedBitmapDrawableFactory 類的 DefaultRoundedBitmapDrawable 方法:
private static class DefaultRoundedBitmapDrawable extends RoundedBitmapDrawable {
    DefaultRoundedBitmapDrawable(Resources res, Bitmap bitmap) {
        super(res, bitmap);
    }

    public void setMipMap(boolean mipMap) {
        if (this.mBitmap != null) {
            BitmapCompat.setHasMipMap(this.mBitmap, mipMap);
            this.invalidateSelf();
        }

    }

    public boolean hasMipMap() {
        return this.mBitmap != null && BitmapCompat.hasMipMap(this.mBitmap);
    }

    void gravityCompatApply(int gravity, int bitmapWidth, int bitmapHeight, Rect bounds, Rect outRect) {
        GravityCompat.apply(gravity, bitmapWidth, bitmapHeight, bounds, outRect, 0);
    }
}
複製程式碼

不難發現,DefaultRoundedBitmapDrawable 繼承至 RoundedBitmapDrawable,並且 DefaultRoundedBitmapDrawable 構造方法實際上呼叫的是 RoundedBitmapDrawable 的構造方法。

  1. 進入 RoundedBitmapDrawable 的構造方法:
RoundedBitmapDrawable(Resources res, Bitmap bitmap) {
    if (res != null) {
        // 獲取螢幕密度
        this.mTargetDensity = res.getDisplayMetrics().densityDpi;
    }

    this.mBitmap = bitmap;
    if (this.mBitmap != null) {
        // 計算 Bitmap 的 Width、Height
        this.computeBitmapSize();
        // 初始化 BitmapShader,今天主角終於出現了
        this.mBitmapShader = new BitmapShader(this.mBitmap, TileMode.CLAMP, TileMode.CLAMP);
    } else {
        this.mBitmapWidth = this.mBitmapHeight = -1;
        this.mBitmapShader = null;
    }

}

//computeBitmapSize
private void computeBitmapSize() {
    this.mBitmapWidth = this.mBitmap.getScaledWidth(this.mTargetDensity);
    this.mBitmapHeight = this.mBitmap.getScaledHeight(this.mTargetDensity);
}
複製程式碼

在 RoundedBitmapDrawable 的構造方法裡,首先獲取到螢幕的密度,其次獲取傳入的 Bitmap 的寬、高,最後初始化 BitmapShader。其實到這裡就可以結束了,因為 RoundedBitmapDrawable 實現圓角的方式已經很明瞭了——通過給 Paint 設定 BitmapShader。當然,這是對於那些已經熟練掌握自定義控制元件的人說的,如果你對自定義控制元件不熟悉,那就接著往下看吧。

  1. 進入 RoundedBitmapDrawable 的 draw 方法:
public void draw(@NonNull Canvas canvas) {
    Bitmap bitmap = this.mBitmap;
    if (bitmap != null) {
        this.updateDstRect();
        if (this.mPaint.getShader() == null) {
            canvas.drawBitmap(bitmap, (Rect)null, this.mDstRect, this.mPaint);
        } else {
            canvas.drawRoundRect(this.mDstRectF, this.mCornerRadius, this.mCornerRadius, this.mPaint);
        }

    }
}
複製程式碼

在 RoundedBitmapDrawable 的 draw 方法中,首先呼叫了 updateDstRect() 方法,然後再根據 BitmapShader 是否為 null 決定到底是直接繪製 Bitmap(canvas.drawBitmap),還是繪製圓角矩形(canvas.drawRoundRect)。

  1. 進入 updateDstRect 方法:
void updateDstRect() {
    //預設情況下,該屬性為 true
    if (this.mApplyGravity) {
        //是否為圓形
        if (this.mIsCircular) {
            //1. 圓形
            
            //計算 Bitmap 短邊
            int minDimen = Math.min(this.mBitmapWidth, this.mBitmapHeight);
            //為 mDstRect 設定 Width、Height 屬性
            this.gravityCompatApply(this.mGravity, minDimen, minDimen, this.getBounds(), this.mDstRect);
            //計算 mDstRect 短邊
            int minDrawDimen = Math.min(this.mDstRect.width(), this.mDstRect.height());
            //比較 mDstRect 的短邊與 mDstRect Width、Height 的關係,進而縮放 mDstRect,以使 mDstRect 為正方形
            int insetX = Math.max(0, (this.mDstRect.width() - minDrawDimen) / 2);
            int insetY = Math.max(0, (this.mDstRect.height() - minDrawDimen) / 2);
            this.mDstRect.inset(insetX, insetY);
            //確定圓角的半徑
            this.mCornerRadius = 0.5F * (float)minDrawDimen;
        } else {
            //2. 矩形
            
            //為 mDstRect 設定 Width、Height 屬性
            this.gravityCompatApply(this.mGravity, this.mBitmapWidth, this.mBitmapHeight, this.getBounds(), this.mDstRect);
        }

        this.mDstRectF.set(this.mDstRect);
        if (this.mBitmapShader != null) {
            //通過 BitmapShader 對應的 Matrix 使 BitmapShader 中的 Bitmap 從 mDstRectF 左上放開始繪製
            this.mShaderMatrix.setTranslate(this.mDstRectF.left, this.mDstRectF.top);
            //將 BitmapShader 中的 Bitmap 縮放至與 mDstRectF 尺寸一樣
            this.mShaderMatrix.preScale(this.mDstRectF.width() / (float)this.mBitmap.getWidth(), this.mDstRectF.height() / (float)this.mBitmap.getHeight());
            this.mBitmapShader.setLocalMatrix(this.mShaderMatrix);
            //為 Paint 設定 BitmapShader
            this.mPaint.setShader(this.mBitmapShader);
        }

        this.mApplyGravity = false;
    }

}
複製程式碼

註釋已經寫的很清楚了,updateDstRect 方法其實主要就是幹三件事:

  • 計算 RoundedBitmapDrawable 所在 DstRectF 的 Width、Height 屬性;
    • RoundedBitmapDrawable 如果為圓形的時候,還要計算矩形(確切地說,應該是正方形)圓角的半徑
  • 計算 BitmapShader 中 Bitmap 的 Width、Height 與 RoundedBitmapDrawable 所在 DstRectF 的 Width、Height 大小關係,進而縮放 Bitmap
  • 為 Paint 設定 BitmapShader

下面是我測試的時候打的斷點的截圖:

使用 RoundedBitmapDrawable 建立圓角頭像詳解

其中用 1、2 標示的地方是計算 RoundedBitmapDrawable 所在 DstRectF 的 Width、Height 屬性,用 3 標出的地方為當 RoundedBitmapDrawable 為圓形時,計算出來的矩形(確切地說,應該是正方形)圓角的半徑。剩下的另外兩個步驟已經在程式碼中註釋的很明顯了,我就不贅述了。

  1. 再回到 draw 方法:
public void draw(@NonNull Canvas canvas) {
    Bitmap bitmap = this.mBitmap;
    if (bitmap != null) {
        this.updateDstRect();
        if (this.mPaint.getShader() == null) {
            canvas.drawBitmap(bitmap, (Rect)null, this.mDstRect, this.mPaint);
        } else {
            canvas.drawRoundRect(this.mDstRectF, this.mCornerRadius, this.mCornerRadius, this.mPaint);
        }

    }
}
複製程式碼

因為 BitmapShader 不為 null,所以進入 drawRoundRect 方法。

因為 mCornerRadius 為 mDstRectF 短邊的一半,所以就有了下面兩張圖:

  • 正方形
使用 RoundedBitmapDrawable 建立圓角頭像詳解
  • 矩形
使用 RoundedBitmapDrawable 建立圓角頭像詳解

4. 容易出錯的地方有哪些?

在使用 RoundedBitmapDrawable 的時候,需要注意地方有:

  1. RoundedBitmapDrawable 引用的圖片資源,須為正方形,否則會被強制壓縮。
  2. ImageView 的 scaleType 須為 fitCenter,否則出現“不良反應”

4.1 RoundedBitmapDrawable 引用的圖片資源,須為正方形,否則會被強制壓縮

其實在分析 RoundedBitmapDrawable 實現原理的時候,就說過,如果 Bitmap 的 Width、Height 與 RoundedBitmapDrawable 所在 RectF 的 Width、Height 不一致的時候,會被強制縮放。

如下圖所示:

使用 RoundedBitmapDrawable 建立圓角頭像詳解

解決的方法其實也簡單,只需要在向 RoundedBitmapDrawableFactory.create(@NonNull Resources res, @Nullable Bitmap bitmap) 方法傳入 Bitmap 之前判斷 Bitmap 的是否為正方形。如果不是正方形,則手動從 Bitmap 中擷取一個正方形;如果是正方形,則直接將 Bitmap 傳遞給 RoundedBitmapDrawableFactory.create(@NonNull Resources res, @Nullable Bitmap bitmap) 方法。

4.1.1 處理方法:根據傳入的 Bitmap 的短邊將 Bitmap 轉換成正方形
//根據傳入的 Bitmap 的短邊將 Bitmap 轉換成正方形
public static Bitmap transferToSquareBitmap(Bitmap bitmap) {
    if (bitmap == null) {
        return null;
    }
    int bitmapWidth = bitmap.getWidth();
    int bitmapHeight = bitmap.getHeight();
    int squareSideLength = Math.min(bitmapWidth, bitmapHeight);
    Bitmap squareBitmap = Bitmap.createBitmap(squareSideLength, squareSideLength, Bitmap.Config.ARGB_8888);
    int squareBitmapWidth = squareBitmap.getWidth();
    int squareBitmapHeight = squareBitmap.getHeight();
    int deltaX, deltaY;
    if(bitmapWidth > squareBitmapWidth){
        deltaX = - (bitmapWidth - squareBitmapWidth)/2;
    }else {
        deltaX = (bitmapWidth - squareBitmapWidth)/2;
    }
    if(bitmapHeight > squareBitmapHeight){
        deltaY = - (bitmapHeight/2 - squareBitmapHeight/2);
    }else {
        deltaY = (bitmapHeight/2 - squareBitmapHeight/2);
    }
    Canvas squareCanvas = new Canvas(squareBitmap);
    squareCanvas.drawBitmap(bitmap, deltaX, deltaY, null);
    return squareBitmap;
}
複製程式碼
4.1.2 測試
//第一步
Bitmap circleBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tiger);
//將 Bitmap 轉換成正方形
circleBitmap = BitmapUtils.transferToSquareBitmap(circleBitmap);
RoundedBitmapDrawable circleDrawable = RoundedBitmapDrawableFactory.create(getResources(), circleBitmap);
//第二步
circleDrawable.setCircular(true);
//第三步
mCircleFitCenterView.setImageDrawable(circleDrawable);
複製程式碼

最終效果如下:

使用 RoundedBitmapDrawable 建立圓角頭像詳解

4.2 ImageView 的 scaleType 須為 fitCenter,否則出現“不良反應”

接下來分別對下面四種情況,展開討論:

  1. 圓形
    • fitCenter
    • centerCrop
  2. 矩形
    • fitCenter
    • centerCrop
4.2.1 圓形
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical">
        
        <!--android:scaleType="fitCenter"-->
        <ImageView
            android:id="@+id/rounded_bitmap_drawable_circle_fit_center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/padding_small"
            android:background="@color/white"
            android:scaleType="fitCenter"
            android:src="@drawable/tiger"
            />
        
        <!--android:scaleType="centerCrop"-->
        <ImageView
            android:id="@+id/rounded_bitmap_drawable_circle_center_crop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/padding_small"
            android:background="@color/white"
            android:scaleType="centerCrop"
            android:src="@drawable/tiger"/>

    </LinearLayout>
</ScrollView>
複製程式碼
public class RoundedBitmapDrawableTutorialActivity extends AppCompatActivity {

    private ImageView mCircleFitCenterView, mCircleCenterCropView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rounded_bitmap_drawable_tutorial);
        initView();
        initData();
    }

    private void initView(){
        mCircleFitCenterView = findViewById(R.id.rounded_bitmap_drawable_circle_fit_center);
        mCircleCenterCropView = findViewById(R.id.rounded_bitmap_drawable_circle_center_crop);
    }

    private void initData(){
        //第一步
        RoundedBitmapDrawable circleDrawable = RoundedBitmapDrawableFactory.create(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.tiger));
        //第二步
        circleDrawable.setCircular(true);
        //第三步
        mCircleFitCenterView.setImageDrawable(circleDrawable);

        mCircleCenterCropView.setImageDrawable(circleDrawable);
    }

}
複製程式碼

最終效果如下:

使用 RoundedBitmapDrawable 建立圓角頭像詳解

由於此時二者效果一樣,所以,我就把圖拉到了二者的中間,因此,大家看到的是兩個老虎的半張臉。

結論:當 RoundedBitmapDrawable 為圓形時,ImageView 的 scaleType 不為 fitCenter 時,沒有“不良反應”。

4.2.2 矩形
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <!--android:scaleType="fitCenter"-->
        <ImageView
            android:id="@+id/rounded_bitmap_drawable_round_rectangle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/padding_small"
            android:background="@color/white"
            android:scaleType="fitCenter"
            android:src="@drawable/tiger"/>

        <!--android:scaleType="centerCrop"-->
        <ImageView
            android:id="@+id/rounded_bitmap_drawable_round_rectangle_center_crop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/padding_small"
            android:background="@color/white"
            android:scaleType="centerCrop"
            android:src="@drawable/tiger"/>

    </LinearLayout>
</ScrollView>
複製程式碼
public class RoundedBitmapDrawableTutorialActivity extends AppCompatActivity {

    private ImageView mRoundRectangleView, mRoundRectangleCenterCropView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rounded_bitmap_drawable_tutorial);
        initView();
        initData();
    }

    private void initView(){
        mRoundRectangleView = findViewById(R.id.rounded_bitmap_drawable_round_rectangle);
        mRoundRectangleCenterCropView = findViewById(R.id.rounded_bitmap_drawable_round_rectangle_center_crop);
    }

    private void initData(){
        Bitmap roundRectangleBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tiger);
        //第一步
        RoundedBitmapDrawable roundRectangleDrawable = RoundedBitmapDrawableFactory.create(getResources(), roundRectangleBitmap);
        //第二步
        roundRectangleDrawable.setCornerRadius((mViewWidth < mViewHeight ? mViewWidth : mViewHeight)/32);
        //第三步
        mRoundRectangleView.setImageDrawable(roundRectangleDrawable);


        mRoundRectangleCenterCropView.setImageDrawable(roundRectangleDrawable);
    }

}
複製程式碼

最終效果如下:

使用 RoundedBitmapDrawable 建立圓角頭像詳解

由上圖可知,scaleType 為 fitCenter 的 ImageView 圓角正常顯示,而 scaleType 為 centerCrop 的 ImageView 圓角未正常顯示。

原因其實很簡單,因為當 ImageView scaleType 為 centerCrop 時,當 Drawable 尺寸比 ImageView 尺寸大時,Drawable 短邊將縮小至與 ImageView 對應邊相等,Drawable 長邊根據相應的縮放係數進行縮放,之後將 Drawable 中間顯示在 ImageView 中間;當 Drawable 尺寸比 ImageView 尺寸小時,Drawable 短邊放大至與 ImageView 對應邊相等,Drawable 長邊根據相應的縮放係數進行縮放,之後將 Drawable 中間顯示在 ImageView 中間。

由上圖中 scaleType 為 fitCenter 的 ImageView 顯示效果可知,轉換之後的 Drawable 尺寸比 ImageView 尺寸小,因此此時會將 Drawable 短邊放大至與 ImageView 對應邊相等、長邊根據相應的縮放係數進行縮放。也就是說,不是 Drawable 未被轉換成圓角,而是 Drawable 的圓角超出了 Drawable 所在 ImageView 的顯示範圍。

驗證這個結論到底正不正確其實也很簡單,只用將 ImageView 的 scaleType 設定為能滿足下面條件的:

當 Drawable 尺寸比 ImageView 尺寸小時,Drawable 不進行任何處理,直接顯示在 ImageView 中間。

而 CENTER_INSIDE 剛好滿足此條件。

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <!--android:scaleType="fitCenter"-->
        <ImageView
            android:id="@+id/rounded_bitmap_drawable_round_rectangle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/padding_small"
            android:background="@color/white"
            android:scaleType="fitCenter"
            android:src="@drawable/tiger" />

        <!--android:scaleType="centerInside"-->
        <ImageView
            android:id="@+id/rounded_bitmap_drawable_round_rectangle_center_crop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/padding_small"
            android:background="@color/white"
            android:scaleType="centerInside"
            android:src="@drawable/tiger" />

    </LinearLayout>
</ScrollView>
複製程式碼

最終效果如下:

使用 RoundedBitmapDrawable 建立圓角頭像詳解

將 ImageView 的 scaleType 設定為 centerInside 之後,第二個 ImageView 的圓角又回來了,成功驗證上面的猜想。

對 ImageView scaleType 屬性不瞭解的人可以看我的另外一篇文章:

這一次,徹底幫你搞明白 ImageView ScaleType

5. 如何將 RoundedBitmapDrawable 封裝成一個工具類?

說了這麼多了,想必大家都已經掌握如何自定義圓角頭像了,接下來,我們將 RoundedBitmapDrawable 封裝成一個工具類,這樣在後面使用的時候,就可以直接拿來用了。

首先,要能區分目標 Drawable 是圓形還是矩形,因此,有了用於區分 Drawable 形狀的泛型類:

public enum DrawableShape {

    CIRCLE,
    RECTANGLE

}
複製程式碼

其次,要能自定義轉換之後的 Drawable 的尺寸,另外,如果是矩形,還能定義矩形圓角的半徑。於是有了下面這個類:

public class RoundedBitmapDrawableUtils {

    public static Drawable getRoundedDrawable(Context context, Bitmap bitmap, DrawableShape drawableShape, float newWidth, float newHeight, float cornerRadius) {
        if (bitmap == null) {
            return null;
        }
        if(drawableShape == null){
            drawableShape = DrawableShape.CIRCLE;
        }
        int bitmapWidth = bitmap.getWidth();
        int bitmapHeight = bitmap.getHeight();
        if(newWidth != 0 && newHeight != 0){
            float scaleRatio = 0;
            if(Math.min(bitmapWidth, bitmapHeight) > Math.min(newWidth, newHeight)){
                scaleRatio = Math.min(newWidth, newHeight) / Math.min(bitmapWidth, bitmapHeight);
            }else if(Math.min(bitmapWidth, bitmapHeight) <= Math.min(newWidth, newHeight)){
                scaleRatio = Math.min(newWidth, newHeight) / Math.min(bitmapWidth, bitmapHeight);
            }
            Matrix matrix = new Matrix();
            matrix.postScale(scaleRatio, scaleRatio);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false);
            bitmapWidth = bitmap.getWidth();
            bitmapHeight = bitmap.getHeight();
        }

        Bitmap dstBitmap;
        int dstBitmapWidth, dstBitmapHeight;
        int deltaX, deltaY;
        Canvas dstCanvas;
        RoundedBitmapDrawable dstDrawable = null;

        switch (drawableShape){
            case CIRCLE:
                dstBitmap = Bitmap.createBitmap(Math.min(bitmapWidth, bitmapHeight), Math.min(bitmapWidth, bitmapHeight), Bitmap.Config.ARGB_8888);
                dstBitmapWidth = dstBitmap.getWidth();
                dstBitmapHeight = dstBitmap.getHeight();
                if(bitmapWidth > dstBitmapWidth){
                    deltaX = - (bitmapWidth/2 - dstBitmapWidth/2);
                }else {
                    deltaX = (bitmapWidth/2 - dstBitmapWidth/2);
                }
                if(bitmapHeight > dstBitmapHeight){
                    deltaY = - (bitmapHeight/2 - dstBitmapHeight/2);
                }else {
                    deltaY = (bitmapHeight/2 - dstBitmapHeight/2);
                }
                dstCanvas = new Canvas(dstBitmap);
                dstCanvas.drawBitmap(bitmap, deltaX, deltaY, null);
                dstDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), dstBitmap);
                dstDrawable.setCircular(true);
                break;
            case RECTANGLE:
                dstBitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
                dstBitmapWidth = dstBitmap.getWidth();
                dstBitmapHeight = dstBitmap.getHeight();
                if(bitmapWidth > dstBitmapWidth){
                    deltaX = - (bitmapWidth/2 - dstBitmapWidth/2);
                }else {
                    deltaX = (bitmapWidth/2 - dstBitmapWidth/2);
                }
                if(bitmapHeight > dstBitmapHeight){
                    deltaY = - (bitmapHeight/2 - dstBitmapHeight/2);
                }else {
                    deltaY = (bitmapHeight/2 - dstBitmapHeight/2);
                }
                dstCanvas = new Canvas(dstBitmap);
                dstCanvas.drawBitmap(bitmap, deltaX, deltaY, null);
                dstDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), dstBitmap);
                dstDrawable.setCornerRadius(cornerRadius);
                break;
        }

        return dstDrawable;
    }

}
複製程式碼

只能傳 Bitmap?!侷限是不是有點大?馬上改一下:

public class RoundedBitmapDrawableUtils {

    public static Drawable getRoundedDrawable(Context context, String pathName, DrawableShape drawableShape, float newWidth, float newHeight, float cornerRadius){
        return getRoundedDrawable(context, BitmapFactory.decodeFile(pathName), drawableShape, newWidth, newHeight, cornerRadius);
    }

    public static Drawable getRoundedDrawable(Context context, int id, DrawableShape drawableShape, float newWidth, float newHeight, float cornerRadius){
        return getRoundedDrawable(context, BitmapFactory.decodeResource(context.getResources(), id), drawableShape, newWidth, newHeight, cornerRadius);
    }

    public static Drawable getRoundedDrawable(Context context, InputStream is, DrawableShape drawableShape, float newWidth, float newHeight, float cornerRadius){
        return getRoundedDrawable(context, BitmapFactory.decodeStream(is), drawableShape, newWidth, newHeight, cornerRadius);
    }

    public static Drawable getRoundedDrawable(Context context, Bitmap bitmap, DrawableShape drawableShape, float newWidth, float newHeight, float cornerRadius) {
        if (bitmap == null) {
            return null;
        }
        if(drawableShape == null){
            drawableShape = DrawableShape.CIRCLE;
        }
        int bitmapWidth = bitmap.getWidth();
        int bitmapHeight = bitmap.getHeight();
        if(newWidth != 0 && newHeight != 0){
            float scaleRatio = 0;
            if(Math.min(bitmapWidth, bitmapHeight) > Math.min(newWidth, newHeight)){
                scaleRatio = Math.min(newWidth, newHeight) / Math.min(bitmapWidth, bitmapHeight);
            }else if(Math.min(bitmapWidth, bitmapHeight) <= Math.min(newWidth, newHeight)){
                scaleRatio = Math.min(newWidth, newHeight) / Math.min(bitmapWidth, bitmapHeight);
            }
            Matrix matrix = new Matrix();
            matrix.postScale(scaleRatio, scaleRatio);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false);
            bitmapWidth = bitmap.getWidth();
            bitmapHeight = bitmap.getHeight();
        }

        Bitmap dstBitmap;
        int dstBitmapWidth, dstBitmapHeight;
        int deltaX, deltaY;
        Canvas dstCanvas;
        RoundedBitmapDrawable dstDrawable = null;

        switch (drawableShape){
            case CIRCLE:
                dstBitmap = Bitmap.createBitmap(Math.min(bitmapWidth, bitmapHeight), Math.min(bitmapWidth, bitmapHeight), Bitmap.Config.ARGB_8888);
                dstBitmapWidth = dstBitmap.getWidth();
                dstBitmapHeight = dstBitmap.getHeight();
                if(bitmapWidth > dstBitmapWidth){
                    deltaX = - (bitmapWidth/2 - dstBitmapWidth/2);
                }else {
                    deltaX = (bitmapWidth/2 - dstBitmapWidth/2);
                }
                if(bitmapHeight > dstBitmapHeight){
                    deltaY = - (bitmapHeight/2 - dstBitmapHeight/2);
                }else {
                    deltaY = (bitmapHeight/2 - dstBitmapHeight/2);
                }
                dstCanvas = new Canvas(dstBitmap);
                dstCanvas.drawBitmap(bitmap, deltaX, deltaY, null);
                dstDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), dstBitmap);
                dstDrawable.setCircular(true);
                break;
            case RECTANGLE:
                dstBitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
                dstBitmapWidth = dstBitmap.getWidth();
                dstBitmapHeight = dstBitmap.getHeight();
                if(bitmapWidth > dstBitmapWidth){
                    deltaX = - (bitmapWidth/2 - dstBitmapWidth/2);
                }else {
                    deltaX = (bitmapWidth/2 - dstBitmapWidth/2);
                }
                if(bitmapHeight > dstBitmapHeight){
                    deltaY = - (bitmapHeight/2 - dstBitmapHeight/2);
                }else {
                    deltaY = (bitmapHeight/2 - dstBitmapHeight/2);
                }
                dstCanvas = new Canvas(dstBitmap);
                dstCanvas.drawBitmap(bitmap, deltaX, deltaY, null);
                dstDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), dstBitmap);
                dstDrawable.setCornerRadius(cornerRadius);
                break;
        }

        return dstDrawable;
    }

}
複製程式碼

趕緊試試?

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical">
        <ImageView
            android:id="@+id/rounded_bitmap_drawable_circle_fit_center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/padding_small"
            android:background="@color/white"
            android:scaleType="fitCenter"
            android:src="@drawable/tiger" />

        <ImageView
            android:id="@+id/rounded_bitmap_drawable_round_rectangle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/padding_small"
            android:background="@color/white"
            android:scaleType="fitCenter"
            android:src="@drawable/tiger" />

    </LinearLayout>
</ScrollView>
複製程式碼
public class RoundedBitmapDrawableTutorialActivity extends AppCompatActivity {

    private int mScreenWidth, mScreenHeight, mViewWidth, mViewHeight;
    private ImageView mCircleFitCenterView, mRoundRectangleView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rounded_bitmap_drawable_tutorial);
        getScreenProperty();
        initView();
        initData();
    }

    private void getScreenProperty(){
        mScreenWidth = DisplayMetricsUtil.getScreenWidth(this);
        mScreenHeight = DisplayMetricsUtil.getScreenHeight(this);
        mViewWidth = mScreenWidth * 2/3;
        mViewHeight = mScreenHeight * 2/3;
    }

    private void initView(){
        mCircleFitCenterView = findViewById(R.id.rounded_bitmap_drawable_circle_fit_center);
        mRoundRectangleView = findViewById(R.id.rounded_bitmap_drawable_round_rectangle);
    }

    private void initData(){
        mCircleFitCenterView.setImageDrawable(RoundedBitmapDrawableUtils.getRoundedDrawable(this, BitmapFactory.decodeResource(getResources(), R.drawable.tiger), DrawableShape.CIRCLE, 0, 0, 0));
        mRoundRectangleView.setImageDrawable(RoundedBitmapDrawableUtils.getRoundedDrawable(this, BitmapFactory.decodeResource(getResources(), R.drawable.tiger), DrawableShape.RECTANGLE, mViewWidth, mViewHeight, (mViewWidth < mViewHeight ? mViewWidth : mViewHeight)/32));
    }

}
複製程式碼

最終效果如下:

使用 RoundedBitmapDrawable 建立圓角頭像詳解

還在等什麼,趕緊去試試吧。

6.參考文獻

  1. RoundedBitmapDrawable
  2. RoundedBitmapDrawableFactory
  3. 這一次,徹底幫你搞明白 ImageView ScaleType

相關文章