效果圖
一個仿釘釘群組頭像顯示效果补疑,支持圖片和文字,可以任意組合情龄,非常方便迄汛,代碼量也非常少捍壤,非常適合拿來學(xué)習(xí)骤视。
繪制一個圓形圖片頭像
這里我首先新建了一個畫布,然后把畫布切割成圓形鹃觉,接下來专酗,通過Bitmap的createScaledBitmap把bitmap縮放到指定大小(這里是畫布大械辽取)祷肯,最后把bitmap繪制到畫布上,代碼如下:
final Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Path mPath = new Path();
mPath.addCircle(width/2, height/2, width/2, Path.Direction.CCW);
canvas.clipPath(mPath); //切割畫布
Bitmap bmp = Bitmap.createScaledBitmap(bitmap, mWidth, mHeight, false);
canvas.drawBitmap(bmp, 0, 0, null);
這樣就可以實現(xiàn)圖中第一行第一個的效果了疗隶,是不是很簡單佑笋。
繪制半圓
接下來是第二個,它由左右兩個半圓組成斑鼻,我們看下左半圓蒋纬,按上面的方法把bitmap縮放到畫布大小,我們?nèi)≈虚g部分來展示,所用的方法是Bitmap的createBitmap(Bitmap source, int x, int y, int width, int height)蜀备,它以source為原圖关摇,創(chuàng)建新的圖片,指定起始坐標(biāo)以及新圖像的高寬碾阁。由于是取中間部分输虱,所以起始坐標(biāo)x=mWidth/4,y=0脂凶,寬度width=mWidth/2宪睹,高度height=mHeight,最后調(diào)用canvas的drawBitmap(Bitmap bitmap, float left, float top, Paint paint)進(jìn)行繪制蚕钦,如果是左半部分left=0横堡,top=0,右半部份left=mWidth / 2冠桃,top = 0命贴,代碼如下(marginWhiteWidth 為中間間隔的寬度):
x = mWidth / 4 + marginWhiteWidth / 2;
y = 0;
width = mWidth / 2 - marginWhiteWidth / 2;// 中間留有1px白條
height = mHeight;
//左半部分
left=0;
top=0;
//右半部分
//left=mWidth / 2 + marginWhiteWidth / 2;
//top=0;
// 比例縮放
Bitmap bmp = Bitmap.createScaledBitmap(bitmap, mWidth, mHeight, false);
// 裁取中間部分(從x點裁取置頂距離)
Bitmap dstBmp = Bitmap.createBitmap(bmp, x, y, width, height);
// 繪圖
canvas.drawBitmap(dstBmp, left, top, null);
繪制四分之一圓
//接下來看第四個,繪制四分之一圓食听,把bitmap的寬高縮放到畫布的一半胸蛛,根據(jù)位置調(diào)整drawBitmap方法的left和top就可以了。
dstWidth = mWidth/2 - marginWhiteWidth / 2;
dstHeight = mHeight/2 - marginWhiteWidth / 2;
//左上
left = 0;
top = 0;
//左下
//left = 0;
//top = mHeight/2 + marginWhiteWidth / 2;
//右上
//left = mWidth/2 + marginWhiteWidth / 2;
//top = 0;
//右下
//left = mWidth/2 + marginWhiteWidth / 2;
//top = mHeight/2 + marginWhiteWidth / 2;
// 比例縮放
Bitmap bmp = Bitmap.createScaledBitmap(bitmap, dstWidth, dstHeight, false);
// 繪圖
canvas.drawBitmap(bmp, left, top, null);
繪制一個圓形文字頭像
首先給文字繪制背景
Paint textBgPaint = new Paint();
textBgPaint.setColor(Color.parseColor(bgColer));
canvas.drawRect(bgLeft, bgTop, bgRight, bgBottom, textBgPaint);
調(diào)整bgLeft, bgTop, bgRight, bgBottom的值就可以調(diào)整背景的區(qū)域樱报。
接下來繪制文字
Paint textPaint = new Paint();
textPaint.setColor(Color.WHITE);
textPaint.setTextSize(textSize);
textPaint.setStyle(Paint.Style.FILL);
//該方法即為設(shè)置基線上那個點究竟是left,center,還是right 這里我設(shè)置為center
textPaint.setTextAlign(Paint.Align.CENTER);
Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
float top = fontMetrics.top;//為基線到字體上邊框的距離,即上圖中的top
float bottom = fontMetrics.bottom;//為基線到字體下邊框的距離,即上圖中的bottom
x = mWidth/2;
y = (int) (mHeight/2 - top/2 - bottom/2);//基線中間點的y軸計算公式
canvas.drawText(text, x, y, textPaint);
可以調(diào)整x葬项,y的值來調(diào)整文字的位置,具體請看源碼迹蛤。部分參考自DingDingImage,特此感謝民珍。
源碼