自制圓形文字ICON

序言

在最近的項目中,有一個地方有很多Item,但是沒有相應(yīng)的圖標(biāo),于是和設(shè)計商量用彩色圓形和第一個文字作為圖標(biāo)。于是就寫了這個東西。

效果

這里寫圖片描述

實現(xiàn)

通過繼承Drawable 使用的時候也很簡單如下

 ImageView.setImageDrawable(new ColorCircleDrawable("A",Color.RED));

比較麻煩的是文字居中
感謝博客 Android Canvas drawText實現(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;
        //正確獲取字體的高度,在繪制的時候需要向上偏移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;
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容