自制圆形文字ICON

序言

在最近的项目中,有一个地方有很多Item,但是没有相应的图标,于是和设计商量用彩色圆形和第一个文字作为图标。于是就写了这个东西。

效果

这里写图片描述

实现

通过继承Drawable 使用的时候也很简单如下

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

比较麻烦的是文字居中
感谢博客 Android Canvas drawText实现中文垂直居中 帮我理清了思路

源码

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 标题
     * @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属性有关
        //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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_22706515/article/details/78217747