自制圆形文字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;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值