Android自定義控件之圓形/圓角的實(shí)現(xiàn)代碼
一、問(wèn)題在哪里?
問(wèn)題來(lái)源于app開(kāi)發(fā)中一個(gè)很常見(jiàn)的場(chǎng)景——用戶頭像要展示成圓的:

二、怎么搞?
機(jī)智的我,第一想法就是,切一張中間圓形透明、四周與底色相同、尺寸與頭像相同的蒙板圖片,蓋在頭像上不就完事了嘛,哈哈哈!
在背景純色的前提下,這的確能簡(jiǎn)單解決問(wèn)題,但是如果背景沒(méi)有這么簡(jiǎn)單呢?

在這種不規(guī)則背景下,有兩個(gè)問(wèn)題:
1)、背景圖常常是適應(yīng)手機(jī)寬度縮放,而頭像的尺寸又是固定寬高DP的,所以固定的蒙板圖片是沒(méi)法保證在不同機(jī)型上都和背景圖案吻合的。
2)、在這種非純色背景下,哪天想調(diào)整一下頭像位置就得重新?lián)Q圖片蒙板,實(shí)在是太難維護(hù)了……
所以呢,既然頭像圖片肯定是方的,那就就讓ImageView圓起來(lái)吧。
三、開(kāi)始干活
基本思路是,自定義一個(gè)ImageView,通過(guò)重寫(xiě)onDraw方法畫(huà)出一個(gè)圓形的圖片來(lái):
public class ImageViewPlus extends ImageView{
private Paint mPaintBitmap = new Paint(Paint.ANTI_ALIAS_FLAG);
private Bitmap mRawBitmap;
private BitmapShader mShader;
private Matrix mMatrix = new Matrix();
public ImageViewPlus(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
Bitmap rawBitmap = getBitmap(getDrawable());
if (rawBitmap != null){
int viewWidth = getWidth();
int viewHeight = getHeight();
int viewMinSize = Math.min(viewWidth, viewHeight);
float dstWidth = viewMinSize;
float dstHeight = viewMinSize;
if (mShader == null || !rawBitmap.equals(mRawBitmap)){
mRawBitmap = rawBitmap;
mShader = new BitmapShader(mRawBitmap, TileMode.CLAMP, TileMode.CLAMP);
}
if (mShader != null){
mMatrix.setScale(dstWidth / rawBitmap.getWidth(), dstHeight / rawBitmap.getHeight());
mShader.setLocalMatrix(mMatrix);
}
mPaintBitmap.setShader(mShader);
float radius = viewMinSize / 2.0f;
canvas.drawCircle(radius, radius, radius, mPaintBitmap);
} else {
super.onDraw(canvas);
}
}
private Bitmap getBitmap(Drawable drawable){
if (drawable instanceof BitmapDrawable){
return ((BitmapDrawable)drawable).getBitmap();
} else if (drawable instanceof ColorDrawable){
Rect rect = drawable.getBounds();
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
int color = ((ColorDrawable)drawable).getColor();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawARGB(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color));
return bitmap;
} else {
return null;
}
}
}
分析一下代碼:
canvas.drawCircle 決定了畫(huà)出來(lái)的形狀是圓形,而圓形的內(nèi)容則是通過(guò) mPaintBitmap.setShader 搞定的。
其中,BitmapShader需要設(shè)置Bitmap填充ImageView的方式(CLAMP:拉伸邊緣, MIRROR:鏡像, REPEAT:整圖重復(fù))。
這里其實(shí)設(shè)成什么不重要,因?yàn)槲覀儗?shí)際需要的是將Bitmap按比例縮放成跟ImageView一樣大,而不是預(yù)置的三種效果。
所以,別忘了 mMatrix.setScale 和 mShader.setLocalMatrix 一起用,將圖片縮放一下。
四、更多玩法 —— 支持邊框
看下面的效果圖,如果想給圓形的頭像上加一個(gè)邊框,該怎么搞呢?

public class ImageViewPlus extends ImageView{
private Paint mPaintBitmap = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint mPaintBorder = new Paint(Paint.ANTI_ALIAS_FLAG);
private Bitmap mRawBitmap;
private BitmapShader mShader;
private Matrix mMatrix = new Matrix();
private float mBorderWidth = dip2px(15);
private int mBorderColor = 0xFF0080FF;
public ImageViewPlus(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
Bitmap rawBitmap = getBitmap(getDrawable());
if (rawBitmap != null){
int viewWidth = getWidth();
int viewHeight = getHeight();
int viewMinSize = Math.min(viewWidth, viewHeight);
float dstWidth = viewMinSize;
float dstHeight = viewMinSize;
if (mShader == null || !rawBitmap.equals(mRawBitmap)){
mRawBitmap = rawBitmap;
mShader = new BitmapShader(mRawBitmap, TileMode.CLAMP, TileMode.CLAMP);
}
if (mShader != null){
mMatrix.setScale((dstWidth - mBorderWidth * 2) / rawBitmap.getWidth(), (dstHeight - mBorderWidth * 2) / rawBitmap.getHeight());
mShader.setLocalMatrix(mMatrix);
}
mPaintBitmap.setShader(mShader);
mPaintBorder.setStyle(Paint.Style.STROKE);
mPaintBorder.setStrokeWidth(mBorderWidth);
mPaintBorder.setColor(mBorderColor);
float radius = viewMinSize / 2.0f;
canvas.drawCircle(radius, radius, radius - mBorderWidth / 2.0f, mPaintBorder);
canvas.translate(mBorderWidth, mBorderWidth);
canvas.drawCircle(radius - mBorderWidth, radius - mBorderWidth, radius - mBorderWidth, mPaintBitmap);
} else {
super.onDraw(canvas);
}
}
private Bitmap getBitmap(Drawable drawable){
if (drawable instanceof BitmapDrawable){
return ((BitmapDrawable)drawable).getBitmap();
} else if (drawable instanceof ColorDrawable){
Rect rect = drawable.getBounds();
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
int color = ((ColorDrawable)drawable).getColor();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawARGB(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color));
return bitmap;
} else {
return null;
}
}
private int dip2px(int dipVal)
{
float scale = getResources().getDisplayMetrics().density;
return (int)(dipVal * scale + 0.5f);
}
}
看代碼中,加邊框?qū)嶋H上就是用實(shí)心純色的 Paint 畫(huà)了一個(gè)圓邊,在此基礎(chǔ)上畫(huà)上原來(lái)的頭像即可。
需要的注意的地方有三個(gè):
1)、圓框的半徑不是 radius ,而應(yīng)該是 radius - mBorderWidth / 2.0f 。想象著拿著筆去畫(huà)線,線其實(shí)是畫(huà)在右圖中白色圈的位置,只不過(guò)它很粗。
2)、在ImageView大小不變的基礎(chǔ)上,頭像的實(shí)際大小要比沒(méi)有邊框的時(shí)候小了,所以 mMatrix.setScale 的時(shí)候要把邊框的寬度去掉。
3)、畫(huà)頭像Bitmap的時(shí)候不能直接 canvas.drawCircle(radius, radius, radius - mBorderWidth, mPaintBitmap) ,這樣你會(huì)發(fā)現(xiàn)頭像的右側(cè)和下方邊緣被拉伸了(右圖)
為什么呢?因?yàn)?Paint 默認(rèn)是以左上角為基準(zhǔn)開(kāi)始繪制的,此時(shí)頭像的實(shí)際區(qū)域是右圖中的紅框,而超過(guò)紅框的部分(圓形的右側(cè)和下方),自然被 TileMode.CLAMP效果沿邊緣拉伸了。
所以,需要通過(guò)挪動(dòng)坐標(biāo)系的位置和調(diào)整圓心,才能把頭像畫(huà)在正確的區(qū)域(右圖綠框)中。
五、更多玩法 —— 支持xml配置
既然有了邊框,那如果想配置邊框的寬度和顏色該如何是好呢?
基本上兩個(gè)思路:
1)給ImageViewPlus加上set接口,設(shè)置完成之后通過(guò) invalidate(); 重繪一下即可;
2)在xml里就支持配置一些自定義屬性,這樣用起來(lái)會(huì)方便很多。
這里重點(diǎn)說(shuō)一下支持xml配置自定義屬性。
自定義控件要支持xml配置自定義屬性的話,首先需要在 \res\values 里去定義屬性:
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="borderColor" format="color" /> <attr name="borderWidth" format="dimension" /> <declare-styleable name="ImageViewPlus"> <attr name="borderColor" /> <attr name="borderWidth" /> </declare-styleable> </resources>
View attrs_imageviewplus.xml
然后在ImageViewPlus的構(gòu)造函數(shù)中去讀取這些自定義屬性:
private static final int DEFAULT_BORDER_COLOR = Color.TRANSPARENT;
private static final int DEFAULT_BORDER_WIDTH = 0;
public ImageViewPlus(Context context, AttributeSet attrs) {
super(context, attrs);
//取xml文件中設(shè)定的參數(shù)
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ImageViewPlus);
mBorderColor = ta.getColor(R.styleable.ImageViewPlus_borderColor, DEFAULT_BORDER_COLOR);
mBorderWidth = ta.getDimensionPixelSize(R.styleable.ImageViewPlus_borderWidth, dip2px(DEFAULT_BORDER_WIDTH));
ta.recycle();
}
在xml布局中使用自定義屬性:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:snser="http://schemas.android.com/apk/res/cc.snser.imageviewplus"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/wallpaper"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<cc.snser.imageviewplus.ImageViewPlus
android:id="@+id/imgplus"
android:layout_width="200dp"
android:layout_height="300dp"
android:layout_marginBottom="50dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:src="@drawable/img_square"
snser:borderColor="#FF0080FF"
snser:borderWidth="15dp" />
</RelativeLayout>
六、更多玩法 —— 圓角ImageView
搞定了圓形ImageView以及對(duì)應(yīng)的邊框,那如何實(shí)現(xiàn)下面這種圓角的ImageView呢?

其實(shí)原理上一樣,把 canvas.drawCircle 對(duì)應(yīng)改成 canvas.drawRoundRect 就OK了,直接貼代碼吧:
public class ImageViewPlus extends ImageView{
/**
* android.widget.ImageView
*/
public static final int TYPE_NONE = 0;
/**
* 圓形
*/
public static final int TYPE_CIRCLE = 1;
/**
* 圓角矩形
*/
public static final int TYPE_ROUNDED_RECT = 2;
private static final int DEFAULT_TYPE = TYPE_NONE;
private static final int DEFAULT_BORDER_COLOR = Color.TRANSPARENT;
private static final int DEFAULT_BORDER_WIDTH = 0;
private static final int DEFAULT_RECT_ROUND_RADIUS = 0;
private int mType;
private int mBorderColor;
private int mBorderWidth;
private int mRectRoundRadius;
private Paint mPaintBitmap = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint mPaintBorder = new Paint(Paint.ANTI_ALIAS_FLAG);
private RectF mRectBorder = new RectF();
private RectF mRectBitmap = new RectF();
private Bitmap mRawBitmap;
private BitmapShader mShader;
private Matrix mMatrix = new Matrix();
public ImageViewPlus(Context context, AttributeSet attrs) {
super(context, attrs);
//取xml文件中設(shè)定的參數(shù)
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ImageViewPlus);
mType = ta.getInt(R.styleable.ImageViewPlus_type, DEFAULT_TYPE);
mBorderColor = ta.getColor(R.styleable.ImageViewPlus_borderColor, DEFAULT_BORDER_COLOR);
mBorderWidth = ta.getDimensionPixelSize(R.styleable.ImageViewPlus_borderWidth, dip2px(DEFAULT_BORDER_WIDTH));
mRectRoundRadius = ta.getDimensionPixelSize(R.styleable.ImageViewPlus_rectRoundRadius, dip2px(DEFAULT_RECT_ROUND_RADIUS));
ta.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
Bitmap rawBitmap = getBitmap(getDrawable());
if (rawBitmap != null && mType != TYPE_NONE){
int viewWidth = getWidth();
int viewHeight = getHeight();
int viewMinSize = Math.min(viewWidth, viewHeight);
float dstWidth = mType == TYPE_CIRCLE ? viewMinSize : viewWidth;
float dstHeight = mType == TYPE_CIRCLE ? viewMinSize : viewHeight;
float halfBorderWidth = mBorderWidth / 2.0f;
float doubleBorderWidth = mBorderWidth * 2;
if (mShader == null || !rawBitmap.equals(mRawBitmap)){
mRawBitmap = rawBitmap;
mShader = new BitmapShader(mRawBitmap, TileMode.CLAMP, TileMode.CLAMP);
}
if (mShader != null){
mMatrix.setScale((dstWidth - doubleBorderWidth) / rawBitmap.getWidth(), (dstHeight - doubleBorderWidth) / rawBitmap.getHeight());
mShader.setLocalMatrix(mMatrix);
}
mPaintBitmap.setShader(mShader);
mPaintBorder.setStyle(Paint.Style.STROKE);
mPaintBorder.setStrokeWidth(mBorderWidth);
mPaintBorder.setColor(mBorderWidth > 0 ? mBorderColor : Color.TRANSPARENT);
if (mType == TYPE_CIRCLE){
float radius = viewMinSize / 2.0f;
canvas.drawCircle(radius, radius, radius - halfBorderWidth, mPaintBorder);
canvas.translate(mBorderWidth, mBorderWidth);
canvas.drawCircle(radius - mBorderWidth, radius - mBorderWidth, radius - mBorderWidth, mPaintBitmap);
} else if (mType == TYPE_ROUNDED_RECT){
mRectBorder.set(halfBorderWidth, halfBorderWidth, dstWidth - halfBorderWidth, dstHeight - halfBorderWidth);
mRectBitmap.set(0.0f, 0.0f, dstWidth - doubleBorderWidth, dstHeight - doubleBorderWidth);
float borderRadius = mRectRoundRadius - halfBorderWidth > 0.0f ? mRectRoundRadius - halfBorderWidth : 0.0f;
float bitmapRadius = mRectRoundRadius - mBorderWidth > 0.0f ? mRectRoundRadius - mBorderWidth : 0.0f;
canvas.drawRoundRect(mRectBorder, borderRadius, borderRadius, mPaintBorder);
canvas.translate(mBorderWidth, mBorderWidth);
canvas.drawRoundRect(mRectBitmap, bitmapRadius, bitmapRadius, mPaintBitmap);
}
} else {
super.onDraw(canvas);
}
}
private int dip2px(int dipVal)
{
float scale = getResources().getDisplayMetrics().density;
return (int)(dipVal * scale + 0.5f);
}
private Bitmap getBitmap(Drawable drawable){
if (drawable instanceof BitmapDrawable){
return ((BitmapDrawable)drawable).getBitmap();
} else if (drawable instanceof ColorDrawable){
Rect rect = drawable.getBounds();
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
int color = ((ColorDrawable)drawable).getColor();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawARGB(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color));
return bitmap;
} else {
return null;
}
}
}
View ImageViewPlus.java
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:snser="http://schemas.android.com/apk/res/cc.snser.imageviewplus"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/wallpaper"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<cc.snser.imageviewplus.ImageViewPlus
android:id="@+id/imgplus"
android:layout_width="200dp"
android:layout_height="300dp"
android:layout_marginBottom="50dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:src="@drawable/img_rectangle"
snser:type="rounded_rect"
snser:borderColor="#FF0080FF"
snser:borderWidth="10dp"
snser:rectRoundRadius="30dp" />
</RelativeLayout>
View layout
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="type"> <enum name="none" value="0" /> <enum name="circle" value="1" /> <enum name="rounded_rect" value="2" /> </attr> <attr name="borderColor" format="color" /> <attr name="borderWidth" format="dimension" /> <attr name="rectRoundRadius" format="dimension" /> <declare-styleable name="ImageViewPlus"> <attr name="type" /> <attr name="borderColor" /> <attr name="borderWidth" /> <attr name="rectRoundRadius" /> </declare-styleable> </resources> View attrs_imageviewplus.xml
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家學(xué)習(xí)Android軟件編程有所幫助。
- Android實(shí)現(xiàn)圓形圖片或者圓角圖片
- Android將Glide動(dòng)態(tài)加載不同大小的圖片切圓角與圓形的方法
- Android開(kāi)發(fā)使用Drawable繪制圓角與圓形圖案功能示例
- Android自定義Drawable實(shí)現(xiàn)圓形和圓角
- Android中Glide加載圓形圖片和圓角圖片實(shí)例代碼
- Android自定義控件之圓形、圓角ImageView
- Android實(shí)現(xiàn)圓角矩形和圓形ImageView的方式
- Android自定義view實(shí)現(xiàn)圓形、圓角和橢圓圖片(BitmapShader圖形渲染)
- android 實(shí)現(xiàn)圓角圖片解決方案
- Android基于Fresco實(shí)現(xiàn)圓角和圓形圖片
相關(guān)文章
基于Android MarginLeft與MarginStart的區(qū)別(詳解)
下面小編就為大家分享一篇基于Android MarginLeft與MarginStart的區(qū)別(詳解),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2017-12-12
優(yōu)化和瘦身Android APK的六個(gè)小技巧
Android應(yīng)用的大小對(duì)用戶體驗(yàn)和應(yīng)用性能至關(guān)重要,大型APK文件會(huì)增加應(yīng)用的安裝時(shí)間,啟動(dòng)時(shí)間和頁(yè)面加載時(shí)間,降低了用戶體驗(yàn),因此,APK瘦身是Android開(kāi)發(fā)中的重要任務(wù),在本文中,我們將分享6個(gè)小技巧,幫助你優(yōu)化和瘦身Android應(yīng)用,需要的朋友可以參考下2023-11-11
Service與Activity之間的通信(同一進(jìn)程)
這篇文章主要介紹了Service與Activity之間的通信(同一進(jìn)程)的相關(guān)資料,需要的朋友可以參考下2016-03-03
Android如何通過(guò)命令行操作Sqlite3數(shù)據(jù)庫(kù)的方法
這篇文章主要介紹了Android如何通過(guò)命令行操作Sqlite3數(shù)據(jù)庫(kù)的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
Android四大組件之Service(服務(wù))實(shí)例詳解
這篇文章主要介紹了Android四大組件之Service(服務(wù))的用法,結(jié)合實(shí)例形式詳細(xì)分析了Service的基本概念,類型,用法與相關(guān)注意事項(xiàng),需要的朋友可以參考下2016-01-01
Android實(shí)現(xiàn)新增及編輯聯(lián)系人的方法
這篇文章主要介紹了Android實(shí)現(xiàn)新增及編輯聯(lián)系人的方法,是Android應(yīng)用開(kāi)發(fā)常見(jiàn)的功能,需要的朋友可以參考下2014-07-07
Android之禁止ViewPager滑動(dòng)實(shí)現(xiàn)實(shí)例
這篇文章主要介紹了Android之禁止ViewPager滑動(dòng)實(shí)現(xiàn)實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-05-05

