Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義控件實戰:圓形/圓角 ImageView 全解析

編輯:關於 Android 開發

自定義控件實戰:圓形/圓角 ImageView 全解析


一、問題出在哪?

問題來自 App 開發中一個非常常見的場景——用戶頭像往往要展示成圓形:

   

[轉載請保留本文地址:https://www.cnblogs.com/goagent/p/5159126.html] 

二、該怎麼解決?

我一開始的直覺是:切一張中間圓形透明、四周與底色相同、尺寸跟頭像一樣的蒙版圖,蓋在頭像上不就好了?在純色背景的前提下,這招確實簡單有效,但如果背景沒那麼單純呢?

面對這種不規則背景,會出現兩個問題:

1)背景圖通常會隨手機寬度縮放,而頭像是固定寬高 dp 的,所以固定的蒙版圖根本無法保證在不同機型上都跟背景圖案吻合。

2)在非純色背景下,哪天想調整頭像位置就得重新換蒙版圖,實在太難維護了。

所以,既然頭像圖片本身一定是方的,那乾脆就讓 ImageView 自己「圓」起來吧。

[轉載請保留本文地址:https://www.cnblogs.com/goagent/p/5159126.html] 

三、開始動手

基本思路是:自定義一個 ImageView,透過重寫 onDraw 方法畫出圓形圖片:

 1 public class ImageViewPlus extends ImageView{ 2 private Paint mPaintBitmap = new Paint(Paint.ANTI_ALIAS_FLAG); 3 private Bitmap mRawBitmap; 4 private BitmapShader mShader; 5 private Matrix mMatrix = new Matrix(); 6 7 public ImageViewPlus(Context context, AttributeSet attrs) { 8 super(context, attrs); 9 } 10 11 @Override 12 protected void onDraw(Canvas canvas) { 13 Bitmap rawBitmap = getBitmap(getDrawable()); 14 if (rawBitmap != null){ 15 int viewWidth = getWidth(); 16 int viewHeight = getHeight(); 17 int viewMinSize = Math.min(viewWidth, viewHeight); 18 float dstWidth = viewMinSize; 19 float dstHeight = viewMinSize; 20 if (mShader == null || !rawBitmap.equals(mRawBitmap)){ 21 mRawBitmap = rawBitmap; 22 mShader = new BitmapShader(mRawBitmap, TileMode.CLAMP, TileMode.CLAMP); 23 } 24 if (mShader != null){ 25 mMatrix.setScale(dstWidth / rawBitmap.getWidth(), dstHeight / rawBitmap.getHeight()); 26 mShader.setLocalMatrix(mMatrix); 27 } 28 mPaintBitmap.setShader(mShader); 29 float radius = viewMinSize / 2.0f; 30 canvas.drawCircle(radius, radius, radius, mPaintBitmap); 31 } else { 32 super.onDraw(canvas); 33 } 34 } 35 36 private Bitmap getBitmap(Drawable drawable){ 37 if (drawable instanceof BitmapDrawable){ 38 return ((BitmapDrawable)drawable).getBitmap(); 39 } else if (drawable instanceof ColorDrawable){ 40 Rect rect = drawable.getBounds(); 41 int width = rect.right - rect.left; 42 int height = rect.bottom - rect.top; 43 int color = ((ColorDrawable)drawable).getColor(); 44 Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 45 Canvas canvas = new Canvas(bitmap); 46 canvas.drawARGB(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color)); 47 return bitmap; 48 } else { 49 return null; 50 } 51 }

來分析一下關鍵點:canvas.drawCircle 決定了畫出來是圓形,而圓形裡填什麼內容,則是靠 mPaintBitmap.setShader 來搞定。

其中 BitmapShader 需要設定 Bitmap 填充 ImageView 的方式(CLAMP:拉伸邊緣;MIRROR:鏡像;REPEAT:整圖重複)。這裡設成哪一種其實不重要,因為我們真正要的是把 Bitmap 按比例縮放到跟 ImageView 一樣大,而非預設的三種效果。所以別忘了搭配 mMatrix.setScale 和 mShader.setLocalMatrix,把圖片縮放好。

[轉載請保留本文地址:https://www.cnblogs.com/goagent/p/5159126.html] 

四、更多玩法——支援邊框

如果想幫圓形頭像加上一圈邊框,該怎麼做?

      

1 public class ImageViewPlus extends ImageView{ 2 private Paint mPaintBitmap = new Paint(Paint.ANTI_ALIAS_FLAG); 3 private Paint mPaintBorder = new Paint(Paint.ANTI_ALIAS_FLAG); 4 private Bitmap mRawBitmap; 5 private BitmapShader mShader; 6 private Matrix mMatrix = new Matrix(); 7 private float mBorderWidth = dip2px(15); 8 private int mBorderColor = 0xFF0080FF; 9 10 public ImageViewPlus(Context context, AttributeSet attrs) { 11 super(context, attrs); 12 } 13 14 @Override 15 protected void onDraw(Canvas canvas) { 16 Bitmap rawBitmap = getBitmap(getDrawable()); 17 if (rawBitmap != null){ 18 int viewWidth = getWidth(); 19 int viewHeight = getHeight(); 20 int viewMinSize = Math.min(viewWidth, viewHeight); 21 float dstWidth = viewMinSize; 22 float dstHeight = viewMinSize; 23 if (mShader == null || !rawBitmap.equals(mRawBitmap)){ 24 mRawBitmap = rawBitmap; 25 mShader = new BitmapShader(mRawBitmap, TileMode.CLAMP, TileMode.CLAMP); 26 } 27 if (mShader != null){ 28 mMatrix.setScale((dstWidth - mBorderWidth * 2) / rawBitmap.getWidth(), (dstHeight - mBorderWidth * 2) / rawBitmap.getHeight()); 29 mShader.setLocalMatrix(mMatrix); 30 } 31 mPaintBitmap.setShader(mShader); 32 mPaintBorder.setStyle(Paint.Style.STROKE); 33 mPaintBorder.setStrokeWidth(mBorderWidth); 34 mPaintBorder.setColor(mBorderColor); 35 float radius = viewMinSize / 2.0f; 36 canvas.drawCircle(radius, radius, radius - mBorderWidth / 2.0f, mPaintBorder); 37 canvas.translate(mBorderWidth, mBorderWidth); 38 canvas.drawCircle(radius - mBorderWidth, radius - mBorderWidth, radius - mBorderWidth, mPaintBitmap); 39 } else { 40 super.onDraw(canvas); 41 } 42 } 43 44 private Bitmap getBitmap(Drawable drawable){ 45 if (drawable instanceof BitmapDrawable){ 46 return ((BitmapDrawable)drawable).getBitmap(); 47 } else if (drawable instanceof ColorDrawable){ 48 Rect rect = drawable.getBounds(); 49 int width = rect.right - rect.left; 50 int height = rect.bottom - rect.top; 51 int color = ((ColorDrawable)drawable).getColor(); 52 Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 53 Canvas canvas = new Canvas(bitmap); 54 canvas.drawARGB(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color)); 55 return bitmap; 56 } else { 57 return null; 58 } 59 } 60 61 private int dip2px(int dipVal) 62 { 63 float scale = getResources().getDisplayMetrics().density; 64 return (int)(dipVal * scale + 0.5f); 65 } 66 } View Code

加邊框的實作,本質上就是用一個實心純色的 Paint 先畫出一圈圓邊,再在其上畫原本的头像。這裡有三個需要注意的地方:

1)圓框的半徑不是 radius,而應該是 radius - mBorderWidth / 2.0f。可以想像自己拿筆畫線,線其實畫在中間那圈的位置,只是它比較粗。

2)在 ImageView 尺寸不變的前提下,頭像實際變小了,所以 mMatrix.setScale 時要把邊框寬度扣除。

3)畫頭像 Bitmap 時不能直接用 canvas.drawCircle(radius, radius, radius - mBorderWidth, mPaintBitmap),否則你會發現頭像右側與下緣被拉伸了。這是因為 Paint 預設以左上角為基準繪製,超出範圍的部分會被 TileMode.CLAMP 沿邊緣拉伸。因此需要透過移動坐標系並調整圓心,把頭像畫到正確的區域裡。

[轉載請保留本文地址:https://www.cnblogs.com/goagent/p/5159126.html] 

五、更多玩法——支援 XML 配置

既然有了邊框,如果想在 XML 裡配置邊框寬度與顏色該怎麼辦?主要有兩個思路:一是提供 set 接口,設定後呼叫 invalidate() 重繪;二是在 XML 中支援自定義屬性,用起来更方便。這裡重點說說後者。

首先需要在 \res\values 中定義屬性:

1 <?xml version="1.0" encoding="utf-8"?> 2 <resources> 3 <attr name="borderColor" format="color" /> 4 <attr name="borderWidth" format="dimension" /> 5 6 <declare-styleable name="ImageViewPlus"> 7 <attr name="borderColor" /> 8 <attr name="borderWidth" /> 9 </declare-styleable> 10 </resources> View attrs_imageviewplus.xml

接著在構造函數中讀取這些屬性:

1 private static final int DEFAULT_BORDER_COLOR = Color.TRANSPARENT; 2 private static final int DEFAULT_BORDER_WIDTH = 0; 3 4 public ImageViewPlus(Context context, AttributeSet attrs) { 5 super(context, attrs); 6 //取xml文件中設定的參數 7 TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ImageViewPlus); 8 mBorderColor = ta.getColor(R.styleable.ImageViewPlus_borderColor, DEFAULT_BORDER_COLOR); 9 mBorderWidth = ta.getDimensionPixelSize(R.styleable.ImageViewPlus_borderWidth, dip2px(DEFAULT_BORDER_WIDTH)); 10 ta.recycle(); 11 } View Code

在佈局中使用自定義屬性:

1 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" 2 xmlns:tools="https://schemas.android.com/tools" 3 xmlns:snser="https://schemas.android.com/apk/res/cc.snser.imageviewplus" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:background="@drawable/wallpaper" 7 android:orientation="vertical" 8 tools:context="${relativePackage}.${activityClass}" > 9 10 <cc.snser.imageviewplus.ImageViewPlus 11 android:id="@+id/imgplus" 12 android:layout_width="200dp" 13 android:layout_height="300dp" 14 android:layout_marginBottom="50dp" 15 android:layout_centerHorizontal="true" 16 android:layout_alignParentBottom="true" 17 android:src="@drawable/img_square" 18 snser:borderColor="#FF0080FF" 19 snser:borderWidth="15dp" /> 20 21 </RelativeLayout> View Code

[轉載請保留本文地址:https://www.cnblogs.com/goagent/p/5159126.html] 

六、更多玩法——圓角 ImageView

搞定了圓形與邊框,那這種圓角 ImageView 又該如何實現?其實原理相同,只要把 canvas.drawCircle 換成 canvas.drawRoundRect 即可,直接看代碼:

1 public class ImageViewPlus extends ImageView{ 2 /** 3 * android.widget.ImageView 4 */ 5 public static final int TYPE_NONE = 0; 6 /** 7 * 圓形 8 */ 9 public static final int TYPE_CIRCLE = 1; 10 /** 11 * 圓角矩形 12 */ 13 public static final int TYPE_ROUNDED_RECT = 2; 14 15 private static final int DEFAULT_TYPE = TYPE_NONE; 16 private static final int DEFAULT_BORDER_COLOR = Color.TRANSPARENT; 17 private static final int DEFAULT_BORDER_WIDTH = 0; 18 private static final int DEFAULT_RECT_ROUND_RADIUS = 0; 19 20 private int mType; 21 private int mBorderColor; 22 private int mBorderWidth; 23 private int mRectRoundRadius; 24 25 private Paint mPaintBitmap = new Paint(Paint.ANTI_ALIAS_FLAG); 26 private Paint mPaintBorder = new Paint(Paint.ANTI_ALIAS_FLAG); 27 28 private RectF mRectBorder = new RectF(); 29 private RectF mRectBitmap = new RectF(); 30 31 private Bitmap mRawBitmap; 32 private BitmapShader mShader; 33 private Matrix mMatrix = new Matrix(); 34 35 public ImageViewPlus(Context context, AttributeSet attrs) { 36 super(context, attrs); 37 //取xml文件中設定的參數 38 TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ImageViewPlus); 39 mType = ta.getInt(R.styleable.ImageViewPlus_type, DEFAULT_TYPE); 40 mBorderColor = ta.getColor(R.styleable.ImageViewPlus_borderColor, DEFAULT_BORDER_COLOR); 41 mBorderWidth = ta.getDimensionPixelSize(R.styleable.ImageViewPlus_borderWidth, dip2px(DEFAULT_BORDER_WIDTH)); 42 mRectRoundRadius = ta.getDimensionPixelSize(R.styleable.ImageViewPlus_rectRoundRadius, dip2px(DEFAULT_RECT_ROUND_RADIUS)); 43 ta.recycle(); 44 } 45 46 @Override 47 protected void onDraw(Canvas canvas) { 48 Bitmap rawBitmap = getBitmap(getDrawable()); 49 50 if (rawBitmap != null && mType != TYPE_NONE){ 51 int viewWidth = getWidth(); 52 int viewHeight = getHeight(); 53 int viewMinSize = Math.min(viewWidth, viewHeight); 54 float dstWidth = mType == TYPE_CIRCLE ? viewMinSize : viewWidth; 55 float dstHeight = mType == TYPE_CIRCLE ? viewMinSize : viewHeight; 56 float halfBorderWidth = mBorderWidth / 2.0f; 57 float doubleBorderWidth = mBorderWidth * 2; 58 59 if (mShader == null || !rawBitmap.equals(mRawBitmap)){ 60 mRawBitmap = rawBitmap; 61 mShader = new BitmapShader(mRawBitmap, TileMode.CLAMP, TileMode.CLAMP); 62 } 63 if (mShader != null){ 64 mMatrix.setScale((dstWidth - doubleBorderWidth) / rawBitmap.getWidth(), (dstHeight - doubleBorderWidth) / rawBitmap.getHeight()); 65 mShader.setLocalMatrix(mMatrix); 66 } 67 68 mPaintBitmap.setShader(mShader); 69 mPaintBorder.setStyle(Paint.Style.STROKE); 70 mPaintBorder.setStrokeWidth(mBorderWidth); 71 mPaintBorder.setColor(mBorderWidth > 0 ? mBorderColor : Color.TRANSPARENT); 72 73 if (mType == TYPE_CIRCLE){ 74 float radius = viewMinSize / 2.0f; 75 canvas.drawCircle(radius, radius, radius - halfBorderWidth, mPaintBorder); 76 canvas.translate(mBorderWidth, mBorderWidth); 77 canvas.drawCircle(radius - mBorderWidth, radius - mBorderWidth, radius - mBorderWidth, mPaintBitmap); 78 } else if (mType == TYPE_ROUNDED_RECT){ 79 mRectBorder.set(halfBorderWidth, halfBorderWidth, dstWidth - halfBorderWidth, dstHeight - halfBorderWidth); 80 mRectBitmap.set(0.0f, 0.0f, dstWidth - doubleBorderWidth, dstHeight - doubleBorderWidth); 81 float borderRadius = mRectRoundRadius - halfBorderWidth > 0.0f ? mRectRoundRadius - halfBorderWidth : 0.0f; 82 float bitmapRadius = mRectRoundRadius - mBorderWidth > 0.0f ? mRectRoundRadius - mBorderWidth : 0.0f; 83 canvas.drawRoundRect(mRectBorder, borderRadius, borderRadius, mPaintBorder); 84 canvas.translate(mBorderWidth, mBorderWidth); 85 canvas.drawRoundRect(mRectBitmap, bitmapRadius, bitmapRadius, mPaintBitmap); 86 } 87 } else { 88 super.onDraw(canvas); 89 } 90 } 91 92 private int dip2px(int dipVal) 93 { 94 float scale = getResources().getDisplayMetrics().density; 95 return (int)(dipVal * scale + 0.5f); 96 } 97 98 private Bitmap getBitmap(Drawable drawable){ 99 if (drawable instanceof BitmapDrawable){ 100 return ((BitmapDrawable)drawable).getBitmap(); 101 } else if (drawable instanceof ColorDrawable){ 102 Rect rect = drawable.getBounds(); 103 int width = rect.right - rect.left; 104 int height = rect.bottom - rect.top; 105 int color = ((ColorDrawable)drawable).getColor(); 106 Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 107 Canvas canvas = new Canvas(bitmap); 108 canvas.drawARGB(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color)); 109 return bitmap; 110 } else { 111 return null; 112 } 113 } View ImageViewPlus.java 1 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" 2 xmlns:tools="https://schemas.android.com/tools" 3 xmlns:snser="https://schemas.android.com/apk/res/cc.snser.imageviewplus" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:background="@drawable/wallpaper" 7 android:orientation="vertical" 8 tools:context="${relativePackage}.${activityClass}" > 9 10 <cc.snser.imageviewplus.ImageViewPlus 11 android:id="@+id/imgplus" 12 android:layout_width="200dp" 13 android:layout_height="300dp" 14 android:layout_marginBottom="50dp" 15 android:layout_centerHorizontal="true" 16 android:layout_alignParentBottom="true" 17 android:src="@drawable/img_rectangle" 18 snser:type="rounded_rect" 19 snser:borderColor="#FF0080FF" 20 snser:borderWidth="10dp" 21 snser:rectRoundRadius="30dp" /> 22 23 </RelativeLayout> View layout 1 <?xml version="1.0" encoding="utf-8"?> 2 <resources> 3 <attr name="type"> 4 <enum name="none" value="0" /> 5 <enum name="circle" value="1" /> 6 <enum name="rounded_rect" value="2" /> 7 </attr> 8 <attr name="borderColor" format="color" /> 9 <attr name="borderWidth" format="dimension" /> 10 <attr name="rectRoundRadius" format="dimension" /> 11 12 <declare-styleable name="ImageViewPlus"> 13 <attr name="type" /> 14 <attr name="borderColor" /> 15 <attr name="borderWidth" /> 16 <attr name="rectRoundRadius" /> 17 </declare-styleable> 18 </resources> View attrs_imageviewplus.xml

[轉載請保留本文地址:https://www.cnblogs.com/goagent/p/5159126.html] 

七、完結

 

[轉載請保留本文地址:https://www.cnblogs.com/goagent/p/5159126.html] 

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved