20行Android代碼寫一個CircleImageView
一提到弄一個圓形的頭像,很多人馬上會想到用CircleIamgeView,但其實自己寫一個也并不難自己寫的部分也就20行代碼,主要是用到PoterDuffXfermode來設(shè)置兩個圖層交集區(qū)域的顯示方式
首先寫一個繼承自ImageView的控件
public class CircleImageView extends ImageView
然后創(chuàng)建構(gòu)造方法
public CircleImageView(Context context, AttributeSet attrs) { super(context, attrs); }
之后重寫onDraw方法
@Override protected void onDraw(Canvas canvas) { //獲得圖片的寬度 int width=getWidth(); //獲得圖片的高度 int height=getHeight(); //短的二分之一作為半徑 int radius=height>width?width/2:height/2; //重新定義的一個畫布,這一步很關(guān)鍵 Paint mPaint = new Paint(); //抗鋸齒 mPaint.setAntiAlias(true); Bitmap bitmap = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888); Canvas bitmapCanvas = new Canvas(bitmap); super.onDraw(bitmapCanvas); //圓形的框 Bitmap cB = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas cCanv = new Canvas(cB); //在控件中間畫一個 cCanv.drawCircle(width/ 2, height/ 2, radius, mPaint); canvas.drawBitmap(bitmap, 0.0f, 0.0f, mPaint); //dst是后畫的圖形 mPaint.setXfermode(new PorterDuffXfermode( PorterDuff.Mode.DST_IN)); //一定要用之前的畫布,不然會出現(xiàn)邊角是黑色 bitmapCanvas.drawBitmap(cB, 0.0f, 0.0f, mPaint); //給圖形加邊框 Paint paint =new Paint(); paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(5); paint.setColor(Color.BLACK); canvas.drawCircle(width/ 2, height/ 2, radius, paint); }
一個簡單的CircleImageView就做成了,你們還可以把邊框弄成一個屬性還有配置相應(yīng)的方法,讓使用者更加方便的使用
它的用法也是和ImageView一模一樣的
<com.example.jkgeekjk.roadtodevelop3.CircleImageView android:layout_width="match_parent" android:src="@drawable/avastar" android:layout_height="match_parent" />
效果圖:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android使用CircleImageView實現(xiàn)圓形頭像的方法
- Android中使用CircleImageView和Cardview制作圓形頭像的方法
- Android自定義控件仿QQ編輯和選取圓形頭像
- 利用Android中BitmapShader制作自帶邊框的圓形頭像
- Android應(yīng)用中繪制圓形頭像的方法解析
- Android實現(xiàn)本地上傳圖片并設(shè)置為圓形頭像
- Android根據(jù)電話號碼獲得聯(lián)系人頭像實例代碼
- Android手機(jī)拍照或選取圖庫圖片作為頭像
- Android實現(xiàn)從本地圖庫/相機(jī)拍照后裁剪圖片并設(shè)置頭像
- Android利用CircleImageView實現(xiàn)圓形頭像的方法
相關(guān)文章
Android Flutter實現(xiàn)3D動畫效果示例詳解
在Flutter中提供了AnimatedWidget組件用于構(gòu)建可復(fù)用的動畫組件。本文我們用AnimatedWidget來實現(xiàn)組件的3D旋轉(zhuǎn)效果,感興趣的可以了解一下2022-03-03Android編程實現(xiàn)調(diào)用系統(tǒng)分享功能示例
這篇文章主要介紹了Android編程實現(xiàn)調(diào)用系統(tǒng)分享功能,結(jié)合實例形式分析了Android實現(xiàn)針對文字、圖片等元素分享功能的相關(guān)操作技巧,需要的朋友可以參考下2017-01-01Android中實現(xiàn)OkHttp上傳文件到服務(wù)器并帶進(jìn)度
本篇文章主要介紹了Android中實現(xiàn)OkHttp上傳文件到服務(wù)器并帶進(jìn)度,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07