序言
在最近的項(xiàng)目中,有一個(gè)地方有很多Item兔跌,但是沒有相應(yīng)的圖標(biāo)座享,于是和設(shè)計(jì)商量用彩色圓形和第一個(gè)文字作為圖標(biāo)。于是就寫了這個(gè)東西龄减。
效果
這里寫圖片描述
實(shí)現(xiàn)
通過繼承Drawable 使用的時(shí)候也很簡單如下
ImageView.setImageDrawable(new ColorCircleDrawable("A",Color.RED));
比較麻煩的是文字居中
感謝博客 Android Canvas drawText實(shí)現(xiàn)中文垂直居中 幫我理清了思路
源碼
public class ColorCircleDrawable extends Drawable {
String mTitle;
Paint mPaint;
int size;
float titleSpace = 0.5f;
Paint backgroundPaint;
int cx, cy;
private int radius;
private int tx, ty;
/**
*
* @param title 標(biāo)題
* @param color 背景色
*/
public ColorCircleDrawable(String title, int color) {
mTitle = title;
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.WHITE);
//文字水平居中
mPaint.setTextAlign(Paint.Align.CENTER);
backgroundPaint = new Paint();
backgroundPaint.setStyle(Paint.Style.FILL_AND_STROKE);
backgroundPaint.setColor(color);
backgroundPaint.setAntiAlias(true);
}
@Override
public void draw(@NonNull Canvas canvas) {
canvas.drawCircle(cx, cy, radius, backgroundPaint);
//drawText中的项钮,x和文字的Paint的Align屬性有關(guān)
//y是指文字baseLine的位置。
canvas.drawText(mTitle, cx, ty, mPaint);
}
@Override
protected void onBoundsChange(Rect bounds) {
size = Math.min(bounds.height(), bounds.width());
int textSize = (int) (size * titleSpace / mTitle.length());
mPaint.setTextSize(textSize);
radius = size / 2;
cx = bounds.width() / 2;
cy = bounds.height() / 2;
//正確獲取字體的高度希停,在繪制的時(shí)候需要向上偏移fontMetricsInt.bottom
Paint.FontMetricsInt fontMetricsInt = mPaint.getFontMetricsInt();
int fontHeight = fontMetricsInt.bottom - fontMetricsInt.top;
ty = cy + fontHeight / 2 - fontMetricsInt.bottom;
}
@Override
public void setAlpha(@IntRange(from = 0, to = 255) int alpha) {
}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
}
@Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
}