20行Android代碼寫一個CircleImageView
更新時間:2016年08月09日 11:48:06 作者:qq_32198277
這篇文章主要介紹了20行Android代碼寫一個CircleImageView,制作圓形頭像,感興趣的小伙伴們可以參考一下
一提到弄一個圓形的頭像,很多人馬上會想到用CircleIamgeView,但其實自己寫一個也并不難自己寫的部分也就20行代碼,主要是用到PoterDuffXfermode來設置兩個圖層交集區(qū)域的顯示方式
首先寫一個繼承自ImageView的控件
public class CircleImageView extends ImageView
然后創(chuàng)建構造方法
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;
//重新定義的一個畫布,這一步很關鍵
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));
//一定要用之前的畫布,不然會出現邊角是黑色
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就做成了,你們還可以把邊框弄成一個屬性還有配置相應的方法,讓使用者更加方便的使用
它的用法也是和ImageView一模一樣的
<com.example.jkgeekjk.roadtodevelop3.CircleImageView android:layout_width="match_parent" android:src="@drawable/avastar" android:layout_height="match_parent" />
效果圖:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:

