1. 什么是 RoundedBitmapDrawable,它存在的意義是什么?
RoundedBitmapDrawable 是 Android 版本 22.1.0 的時(shí)候加入的,它的主要作用是創(chuàng)建圓角的 Drawable。
A Drawable that wraps a bitmap and can be drawn with rounded corners.
Google 添加此類的原因可能是彌補(bǔ) Android API 中沒有直接支持創(chuàng)建圓角 Drawable 的空缺吧。
2. 怎么用?
RoundedBitmapDrawable 不僅可以創(chuàng)建圓角的 Drawable,還可以創(chuàng)建圓角矩形的 Drawable,接下來(lái),我們就針對(duì)這兩種情況分別討論。
2.1 圓形 Drawable
2.1.1 概述
創(chuàng)建和應(yīng)用 RoundedBitmapDrawable 一共分三步:
- 創(chuàng)建 RoundedBitmapDrawable 對(duì)象;
- 設(shè)置 RoundedBitmapDrawable 為圓形;
- 將 RoundedBitmapDrawable 設(shè)置到 ImageView 上。
2.1.2 詳述
- 創(chuàng)建 RoundedBitmapDrawable 對(duì)象
RoundedBitmapDrawable circleDrawable = RoundedBitmapDrawableFactory.create(@NonNull Resources res, @Nullable Bitmap bitmap);
- 設(shè)置 RoundedBitmapDrawable 為圓形
RoundedBitmapDrawable.setCircular(boolean circular);
- 將 RoundedBitmapDrawable 設(shè)置到 ImageView 上
ImageView.setImageDrawable(@Nullable Drawable drawable);
2.1.3 應(yīng)用實(shí)例
//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);
}
}
最終效果如下:

2.2 圓角矩形 Drawable
2.2.1 概述
創(chuàng)建和應(yīng)用 RoundedBitmapDrawable 一共分三步:
- 創(chuàng)建 RoundedBitmapDrawable 對(duì)象;
- 為 RoundedBitmapDrawable 設(shè)置圓角的半徑;
- 將 RoundedBitmapDrawable 設(shè)置到 ImageView 上。
2.2.2 詳述
- 創(chuàng)建 RoundedBitmapDrawable 對(duì)象
RoundedBitmapDrawable circleDrawable = RoundedBitmapDrawableFactory.create(@NonNull Resources res, @Nullable Bitmap bitmap);
- 為 RoundedBitmapDrawable 設(shè)置圓角的半徑
RoundedBitmapDrawable.setCornerRadius(float cornerRadius);
- 將 RoundedBitmapDrawable 設(shè)置到 ImageView 上
ImageView.setImageDrawable(@Nullable Drawable drawable);
2.2.3 應(yīng)用實(shí)例
//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);
}
}
最終效果如下:

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

修改方法如下:
//第一步
RoundedBitmapDrawable roundRectangleDrawable = RoundedBitmapDrawableFactory.create(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.tiger));
//第二步
roundRectangleDrawable.setCornerRadius((mViewWidth < mViewHeight ? mViewWidth : mViewHeight)/2));
//第三步
mRoundRectangleView.setImageDrawable(roundRectangleDrawable);
是不是很好用?
3. RoundedBitmapDrawable 實(shí)現(xiàn)原理是什么?
知道了怎么用 RoundedBitmapDrawable 之后,讓我們一塊看下,RoundedBitmapDrawable 到底是如何“變圓”的。
- 進(jìn)入 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 的情況,另外一種情況,大家自己去分析吧。
- 進(jìn)入 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);
}
}
不難發(fā)現(xiàn),DefaultRoundedBitmapDrawable 繼承至 RoundedBitmapDrawable,并且 DefaultRoundedBitmapDrawable 構(gòu)造方法實(shí)際上調(diào)用的是 RoundedBitmapDrawable 的構(gòu)造方法。
- 進(jìn)入 RoundedBitmapDrawable 的構(gòu)造方法:
RoundedBitmapDrawable(Resources res, Bitmap bitmap) {
if (res != null) {
// 獲取屏幕密度
this.mTargetDensity = res.getDisplayMetrics().densityDpi;
}
this.mBitmap = bitmap;
if (this.mBitmap != null) {
// 計(jì)算 Bitmap 的 Width、Height
this.computeBitmapSize();
// 初始化 BitmapShader,今天主角終于出現(xiàn)了
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 的構(gòu)造方法里,首先獲取到屏幕的密度,其次獲取傳入的 Bitmap 的寬、高,最后初始化 BitmapShader。其實(shí)到這里就可以結(jié)束了,因?yàn)?RoundedBitmapDrawable 實(shí)現(xiàn)圓角的方式已經(jīng)很明了了——通過(guò)給 Paint 設(shè)置 BitmapShader。當(dāng)然,這是對(duì)于那些已經(jīng)熟練掌握自定義控件的人說(shuō)的,如果你對(duì)自定義控件不熟悉,那就接著往下看吧。
- 進(jìn)入 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 方法中,首先調(diào)用了 updateDstRect() 方法,然后再根據(jù) BitmapShader 是否為 null 決定到底是直接繪制 Bitmap(canvas.drawBitmap),還是繪制圓角矩形(canvas.drawRoundRect)。
- 進(jìn)入 updateDstRect 方法:
void updateDstRect() {
//默認(rèn)情況下,該屬性為 true
if (this.mApplyGravity) {
//是否為圓形
if (this.mIsCircular) {
//1. 圓形
//計(jì)算 Bitmap 短邊
int minDimen = Math.min(this.mBitmapWidth, this.mBitmapHeight);
//為 mDstRect 設(shè)置 Width、Height 屬性
this.gravityCompatApply(this.mGravity, minDimen, minDimen, this.getBounds(), this.mDstRect);
//計(jì)算 mDstRect 短邊
int minDrawDimen = Math.min(this.mDstRect.width(), this.mDstRect.height());
//比較 mDstRect 的短邊與 mDstRect Width、Height 的關(guān)系,進(jìn)而縮放 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 設(shè)置 Width、Height 屬性
this.gravityCompatApply(this.mGravity, this.mBitmapWidth, this.mBitmapHeight, this.getBounds(), this.mDstRect);
}
this.mDstRectF.set(this.mDstRect);
if (this.mBitmapShader != null) {
//通過(guò) BitmapShader 對(duì)應(yīng)的 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 設(shè)置 BitmapShader
this.mPaint.setShader(this.mBitmapShader);
}
this.mApplyGravity = false;
}
}
注釋已經(jīng)寫的很清楚了,updateDstRect 方法其實(shí)主要就是干三件事:
- 計(jì)算 RoundedBitmapDrawable 所在 DstRectF 的 Width、Height 屬性;
- RoundedBitmapDrawable 如果為圓形的時(shí)候,還要計(jì)算矩形(確切地說(shuō),應(yīng)該是正方形)圓角的半徑
- 計(jì)算 BitmapShader 中 Bitmap 的 Width、Height 與 RoundedBitmapDrawable 所在 DstRectF 的 Width、Height 大小關(guān)系,進(jìn)而縮放 Bitmap
- 為 Paint 設(shè)置 BitmapShader
下面是我測(cè)試的時(shí)候打的斷點(diǎn)的截圖:

其中用 1、2 標(biāo)示的地方是計(jì)算 RoundedBitmapDrawable 所在 DstRectF 的 Width、Height 屬性,用 3 標(biāo)出的地方為當(dāng) RoundedBitmapDrawable 為圓形時(shí),計(jì)算出來(lái)的矩形(確切地說(shuō),應(yīng)該是正方形)圓角的半徑。剩下的另外兩個(gè)步驟已經(jīng)在代碼中注釋的很明顯了,我就不贅述了。
- 再回到 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);
}
}
}
因?yàn)?BitmapShader 不為 null,所以進(jìn)入 drawRoundRect 方法。
因?yàn)?mCornerRadius 為 mDstRectF 短邊的一半,所以就有了下面兩張圖:
- 正方形

- 矩形

4. 容易出錯(cuò)的地方有哪些?
在使用 RoundedBitmapDrawable 的時(shí)候,需要注意地方有:
- RoundedBitmapDrawable 引用的圖片資源,須為正方形,否則會(huì)被強(qiáng)制壓縮。
- ImageView 的 scaleType 須為 fitCenter,否則出現(xiàn)“不良反應(yīng)”
4.1 RoundedBitmapDrawable 引用的圖片資源,須為正方形,否則會(huì)被強(qiáng)制壓縮
其實(shí)在分析 RoundedBitmapDrawable 實(shí)現(xiàn)原理的時(shí)候,就說(shuō)過(guò),如果 Bitmap 的 Width、Height 與 RoundedBitmapDrawable 所在 RectF 的 Width、Height 不一致的時(shí)候,會(huì)被強(qiáng)制縮放。
如下圖所示:

解決的方法其實(shí)也簡(jiǎn)單,只需要在向 RoundedBitmapDrawableFactory.create(@NonNull Resources res, @Nullable Bitmap bitmap) 方法傳入 Bitmap 之前判斷 Bitmap 的是否為正方形。如果不是正方形,則手動(dòng)從 Bitmap 中截取一個(gè)正方形;如果是正方形,則直接將 Bitmap 傳遞給 RoundedBitmapDrawableFactory.create(@NonNull Resources res, @Nullable Bitmap bitmap) 方法。
4.1.1 處理方法:根據(jù)傳入的 Bitmap 的短邊將 Bitmap 轉(zhuǎn)換成正方形
//根據(jù)傳入的 Bitmap 的短邊將 Bitmap 轉(zhuǎn)換成正方形
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 測(cè)試
//第一步
Bitmap circleBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tiger);
//將 Bitmap 轉(zhuǎn)換成正方形
circleBitmap = BitmapUtils.transferToSquareBitmap(circleBitmap);
RoundedBitmapDrawable circleDrawable = RoundedBitmapDrawableFactory.create(getResources(), circleBitmap);
//第二步
circleDrawable.setCircular(true);
//第三步
mCircleFitCenterView.setImageDrawable(circleDrawable);
最終效果如下:

4.2 ImageView 的 scaleType 須為 fitCenter,否則出現(xiàn)“不良反應(yīng)”
接下來(lái)分別對(duì)下面四種情況,展開討論:
- 圓形
- fitCenter
- centerCrop
- 矩形
- 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);
}
}
最終效果如下:

由于此時(shí)二者效果一樣,所以,我就把圖拉到了二者的中間,因此,大家看到的是兩個(gè)老虎的半張臉。
結(jié)論:當(dāng) RoundedBitmapDrawable 為圓形時(shí),ImageView 的 scaleType 不為 fitCenter 時(shí),沒有“不良反應(yīng)”。
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);
}
}
最終效果如下:

由上圖可知,scaleType 為 fitCenter 的 ImageView 圓角正常顯示,而 scaleType 為 centerCrop 的 ImageView 圓角未正常顯示。
原因其實(shí)很簡(jiǎn)單,因?yàn)楫?dāng) ImageView scaleType 為 centerCrop 時(shí),當(dāng) Drawable 尺寸比 ImageView 尺寸大時(shí),Drawable 短邊將縮小至與 ImageView 對(duì)應(yīng)邊相等,Drawable 長(zhǎng)邊根據(jù)相應(yīng)的縮放系數(shù)進(jìn)行縮放,之后將 Drawable 中間顯示在 ImageView 中間;當(dāng) Drawable 尺寸比 ImageView 尺寸小時(shí),Drawable 短邊放大至與 ImageView 對(duì)應(yīng)邊相等,Drawable 長(zhǎng)邊根據(jù)相應(yīng)的縮放系數(shù)進(jìn)行縮放,之后將 Drawable 中間顯示在 ImageView 中間。
由上圖中 scaleType 為 fitCenter 的 ImageView 顯示效果可知,轉(zhuǎn)換之后的 Drawable 尺寸比 ImageView 尺寸小,因此此時(shí)會(huì)將 Drawable 短邊放大至與 ImageView 對(duì)應(yīng)邊相等、長(zhǎng)邊根據(jù)相應(yīng)的縮放系數(shù)進(jìn)行縮放。也就是說(shuō),不是 Drawable 未被轉(zhuǎn)換成圓角,而是 Drawable 的圓角超出了 Drawable 所在 ImageView 的顯示范圍。
驗(yàn)證這個(gè)結(jié)論到底正不正確其實(shí)也很簡(jiǎn)單,只用將 ImageView 的 scaleType 設(shè)置為能滿足下面條件的:
當(dāng) Drawable 尺寸比 ImageView 尺寸小時(shí),Drawable 不進(jìn)行任何處理,直接顯示在 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>
最終效果如下:

將 ImageView 的 scaleType 設(shè)置為 centerInside 之后,第二個(gè) ImageView 的圓角又回來(lái)了,成功驗(yàn)證上面的猜想。
對(duì) ImageView scaleType 屬性不了解的人可以看我的另外一篇文章:
這一次,徹底幫你搞明白 ImageView ScaleType
5. 如何將 RoundedBitmapDrawable 封裝成一個(gè)工具類?
說(shuō)了這么多了,想必大家都已經(jīng)掌握如何自定義圓角頭像了,接下來(lái),我們將 RoundedBitmapDrawable 封裝成一個(gè)工具類,這樣在后面使用的時(shí)候,就可以直接拿來(lái)用了。
首先,要能區(qū)分目標(biāo) Drawable 是圓形還是矩形,因此,有了用于區(qū)分 Drawable 形狀的泛型類:
public enum DrawableShape {
CIRCLE,
RECTANGLE
}
其次,要能自定義轉(zhuǎn)換之后的 Drawable 的尺寸,另外,如果是矩形,還能定義矩形圓角的半徑。于是有了下面這個(gè)類:
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?!局限是不是有點(diǎn)大?馬上改一下:
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));
}
}
最終效果如下:

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