自制圆形文字ICON

作者: zhuguohui | 来源:发表于2017-10-12 18:01 被阅读250次

序言

在最近的项目中,有一个地方有很多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;
    }
}

相关文章

  • 自制圆形文字ICON

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

  • 圆形icon绘制方法

    上面这些小icon很多初学者都会选择使用截图来实现,下面给出使用css画出来的方法。 .icon{ backg...

  • Button上icon加文字

    我们常常需要做一个button上面既有icon又有文字。也许左icon右文字,或者上icon下文字。UIButto...

  • 「好奇心日报」版式设计观察记

    观「好奇心日报」,随手摘录一些值得借鉴的版式设计。 ▎巧用icon第一眼看到的不是文字,而是三个黄色的圆形,这是给...

  • UGUI雷达图《三》--- 圆形Image

    今天我们来实现一个圆形Image,如下图。(哈,这次其实不是画雷达图了,而是画圆形Icon,不过其原理和之前的雷达...

  • 不规则的文字环绕问题

    常见的文字环绕效果: 1.圆形环绕效果 css代码: 2.椭圆形文字环绕 css代码: 3.三角形文字环绕

  • Quartz2D 绘图

    绘制文字 绘制图片 裁剪圆形图片

  • 5-5 文字编排 -- 圆形文字

    知识储备 1.SVG Path 小测试 最终效果(扣子丑了点): html 解释:透过SVG的基本方式,在

  • 唯美古风句子|甜心情话

    文字素材于网络,侵删。 图片自制

  • 使用layerDrawable绘制icon

    需求里面有个icon这这样的 想尝试下用xml 直接绘制思路是一个layer-list 里面3个item 白色圆形...

网友评论

    本文标题: 自制圆形文字ICON

    本文链接:https://www.haomeiwen.com/subject/fyuoyxtx.html