抖音网红罗盘时钟

前言

周末无事,看到抖音上罗盘时钟壁纸很炫酷,所以想着自己动手实践一下,顺便复习下自定义View的相关知识。

实现效果

GIF.gif

上图为最终的效果,一个自定义View实现

实现过程

首先确定View宽高,重新测量使画布宽高相等

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        int width = Math.min(widthSize, heightSize);
        if (widthMode == MeasureSpec.UNSPECIFIED) {
            width = heightSize + getPaddingRight() + getPaddingLeft();
        } else if (heightMode == MeasureSpec.UNSPECIFIED) {
            width = widthSize + getPaddingRight() + getPaddingLeft();
        }
        setMeasuredDimension(width, width);
    }

为防止横屏出错,需要在尺寸改变的时候重新测量

@Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        width = w;
        height = h;
        if (width > height) {
            radius = height / 2;
        } else {
            radius = width / 2;
        }
        super.onSizeChanged(w, h, oldw, oldh);
    }

在资源文件中创建attrs.xml,方便通过布局配置样式:

<declare-styleable name="CompassView">
        <!--中间姓氏-->
        <attr name="centerText" format="string"/>
        <!--中间文本大小-->
        <attr name="centerSize" format="dimension"/>
        <!--时钟字体大小-->
        <attr name="clockTextSize" format="dimension"/>
        <!--时钟字体颜色-->
        <attr name="compassColor" format="color"/>
        <!--当前时间颜色-->
        <attr name="selectColor" format="color"/>
    </declare-styleable>

整个View分四部分:

  • 中间姓氏
  • 12小时制时
  • 分钟
  • 秒钟

中间姓氏代码实现

    /**
     * 初始化
     *
     * @param context 上下文对象
     * @param attrs   资源
     */
    private void init(Context context, @Nullable AttributeSet attrs) {
        if (null != attrs) {
            TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CompassView);
            centerText = array.getString(R.styleable.CompassView_centerText);
            centerSize = array.getDimension(R.styleable.CompassView_centerSize, 18);
            clockTextSize = array.getDimension(R.styleable.CompassView_clockTextSize, 14);
            compassColor = array.getColor(R.styleable.CompassView_compassColor, ContextCompat.getColor(context, R.color.colorGray));
            selectColor = array.getColor(R.styleable.CompassView_selectColor, ContextCompat.getColor(context, R.color.colorWhite));
            array.recycle();
        }
        //初始化姓氏画笔
        bounds = new Rect();
        clockBounds = new Rect();
        txtPaint = new Paint();
        txtPaint.setColor(selectColor);
        txtPaint.setTextAlign(Paint.Align.CENTER);
        txtPaint.setTextSize(centerSize);
        ,,,,
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        ,,,,
        //测量文本
        txtPaint.getTextBounds(centerText, 0, centerText.length(), bounds);
        //画姓氏
        canvas.drawText(centerText, radius, radius - (float) (bounds.top + bounds.bottom) / 2, txtPaint);
        ,,,,
    }

画时分秒罗盘

        //画小时刻度
        for (int i = 0; i < shis.length; i++) {
            double degree = (i + 12 - hour + 4) * rr2;
            float x = (float) (radius + centerSize * Math.sin(degree));
            float y = (float) (radius - centerSize * Math.cos(degree));
            canvas.save();
            canvas.rotate((float) (degree / Math.PI * 180 - 90), x, y);
            sPaint.getTextBounds(shis[i], 0, shis[i].length(), clockBounds);
            if (i == hour - 1) {
                sPaint.setColor(selectColor);
            } else {
                sPaint.setColor(compassColor);
            }
            canvas.drawText(shis[i], x, y - (float) (clockBounds.top + clockBounds.bottom) / 2, sPaint);
            canvas.restore();
        }
        //画分
        for (int i = 0; i < fenmiaos.length; i++) {
            double degree = (i + 60 - minute + 15) * rr;
            float x = (float) (radius + (radius / 2 - clockTextSize) * Math.sin(degree));
            float y = (float) (radius - (radius / 2 - clockTextSize) * Math.cos(degree));
            canvas.save();
            canvas.rotate((float) (degree / Math.PI * 180 - 90), x, y);
            fPaint.getTextBounds(fenmiaos[i] + "分", 0, (fenmiaos[i] + "分").length(), clockBounds);
            if (i == minute) {
                fPaint.setColor(selectColor);
            } else {
                fPaint.setColor(compassColor);
            }
            canvas.drawText(fenmiaos[i] + "分", x, y - (float) (clockBounds.top + clockBounds.bottom) / 2, fPaint);
            canvas.restore();
        }
        //画秒
        for (int i = 0; i < fenmiaos.length; i++) {
            double degree = (i + 60 - second + 15) * rr;
            float x = (float) (radius + (radius - clockTextSize * 4) * Math.sin(degree));
            float y = (float) (radius - (radius - clockTextSize * 4) * Math.cos(degree));
            canvas.save();
            canvas.rotate((float) (degree / Math.PI * 180 - 90), x, y);
            mPaint.getTextBounds(fenmiaos[i] + "秒", 0, (fenmiaos[i] + "秒").length(), clockBounds);
            if (i == second) {
                mPaint.setColor(selectColor);
            } else {
                mPaint.setColor(compassColor);
            }
            canvas.drawText(fenmiaos[i] + "秒", x, y - (float) (clockBounds.top + clockBounds.bottom) / 2, mPaint);
            canvas.restore();
        }

完整代码

/**
 * @author limh
 * @function
 * @date 2019/4/14 9:51
 */
public class CompassView extends View {
    private String TAG = "CompassView";
    private String[] shis = {"一点", "两点", "三点", "四点", "五点", "六点", "七点", "八点", "九点", "十点", "十一点", "十二点"};
    private String[] fenmiaos = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十",
            "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十",
            "二十一", "二十二", "二十三", "二十四", "二十五", "二十六", "二十七", "二十八", "二十九", "三十",
            "三十一", "三十二", "三十三", "三十四", "三十五", "三十六", "三十七", "三十八", "三十九", "四十",
            "四十一", "四十二", "四十三", "四十四", "四十五", "四十六", "四十七", "四十八", "四十九", "五十",
            "五十一", "五十二", "五十三", "五十四", "五十五", "五十六", "五十七", "五十八", "五十九"};
    private Double rr = 2 * Math.PI / 60;//2π即360度的圆形f份成60份,一秒钟与一钟
    private Double rr2 = 2 * Math.PI / 12;//2π圆形份成12份,圆形显示12个小时的刻度
    //半径
    private int radius;
    //宽
    private int width;
    //高
    private int height;

    //画笔 时  分 秒
    private Paint sPaint;
    private Paint fPaint;
    private Paint mPaint;
    //中间文字
    private Paint txtPaint;
    private Rect bounds;
    private Rect clockBounds;

    private String centerText = "李";
    private float centerSize = 18f;
    private float clockTextSize = 14f;
    private int compassColor = 0xFFDDDDDD;
    private int selectColor = 0xFF000000;

    private int hour = 1;
    private int minute = 0;
    private int second = 0;

    public CompassView(Context context) {
        super(context);
        init(context, null);
    }

    public CompassView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CompassView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    /**
     * 初始化
     *
     * @param context 上下文对象
     * @param attrs   资源
     */
    private void init(Context context, @Nullable AttributeSet attrs) {
        if (null != attrs) {
            TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CompassView);
            centerText = array.getString(R.styleable.CompassView_centerText);
            centerSize = array.getDimension(R.styleable.CompassView_centerSize, 18);
            clockTextSize = array.getDimension(R.styleable.CompassView_clockTextSize, 14);
            compassColor = array.getColor(R.styleable.CompassView_compassColor, ContextCompat.getColor(context, R.color.colorGray));
            selectColor = array.getColor(R.styleable.CompassView_selectColor, ContextCompat.getColor(context, R.color.colorWhite));
            array.recycle();
        }
        bounds = new Rect();
        clockBounds = new Rect();
        txtPaint = new Paint();
        txtPaint.setColor(selectColor);
        txtPaint.setTextAlign(Paint.Align.CENTER);
        txtPaint.setTextSize(centerSize);

        sPaint = new Paint();
        sPaint.setColor(compassColor);
        sPaint.setTextAlign(Paint.Align.CENTER);
        sPaint.setTextSize(clockTextSize);

        fPaint = new Paint();
        fPaint.setColor(compassColor);
        fPaint.setTextAlign(Paint.Align.LEFT);
        fPaint.setTextSize(clockTextSize);

        mPaint = new Paint();
        mPaint.setColor(compassColor);
        mPaint.setTextAlign(Paint.Align.LEFT);
        mPaint.setTextSize(clockTextSize);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        updateTime();
        //测量文本
        txtPaint.getTextBounds(centerText, 0, centerText.length(), bounds);
        //画姓氏
        canvas.drawText(centerText, radius, radius - (float) (bounds.top + bounds.bottom) / 2, txtPaint);
        //画小时刻度
        for (int i = 0; i < shis.length; i++) {
            double degree = (i + 12 - hour + 4) * rr2;
            float x = (float) (radius + centerSize * Math.sin(degree));
            float y = (float) (radius - centerSize * Math.cos(degree));
            canvas.save();
            canvas.rotate((float) (degree / Math.PI * 180 - 90), x, y);
            sPaint.getTextBounds(shis[i], 0, shis[i].length(), clockBounds);
            if (i == hour - 1) {
                sPaint.setColor(selectColor);
            } else {
                sPaint.setColor(compassColor);
            }
            canvas.drawText(shis[i], x, y - (float) (clockBounds.top + clockBounds.bottom) / 2, sPaint);
            canvas.restore();
        }
        //画分
        for (int i = 0; i < fenmiaos.length; i++) {
            double degree = (i + 60 - minute + 15) * rr;
            float x = (float) (radius + (radius / 2 - clockTextSize) * Math.sin(degree));
            float y = (float) (radius - (radius / 2 - clockTextSize) * Math.cos(degree));
            canvas.save();
            canvas.rotate((float) (degree / Math.PI * 180 - 90), x, y);
            fPaint.getTextBounds(fenmiaos[i] + "分", 0, (fenmiaos[i] + "分").length(), clockBounds);
            if (i == minute) {
                fPaint.setColor(selectColor);
            } else {
                fPaint.setColor(compassColor);
            }
            canvas.drawText(fenmiaos[i] + "分", x, y - (float) (clockBounds.top + clockBounds.bottom) / 2, fPaint);
            canvas.restore();
        }
        //画秒
        for (int i = 0; i < fenmiaos.length; i++) {
            double degree = (i + 60 - second + 15) * rr;
            float x = (float) (radius + (radius - clockTextSize * 4) * Math.sin(degree));
            float y = (float) (radius - (radius - clockTextSize * 4) * Math.cos(degree));
            canvas.save();
            canvas.rotate((float) (degree / Math.PI * 180 - 90), x, y);
            mPaint.getTextBounds(fenmiaos[i] + "秒", 0, (fenmiaos[i] + "秒").length(), clockBounds);
            if (i == second) {
                mPaint.setColor(selectColor);
            } else {
                mPaint.setColor(compassColor);
            }
            canvas.drawText(fenmiaos[i] + "秒", x, y - (float) (clockBounds.top + clockBounds.bottom) / 2, mPaint);
            canvas.restore();
        }
        //每秒刷新
        postInvalidateDelayed(1000);
    }

    /**
     * 更新当前时间
     */
    private void updateTime() {
        Calendar calendar = Calendar.getInstance();
        hour = calendar.get(Calendar.HOUR);//获取小时,12小时制
        minute = calendar.get(Calendar.MINUTE);//获取分钟
        second = calendar.get(Calendar.SECOND);//获取秒
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        width = w;
        height = h;
        if (width > height) {
            radius = height / 2;
        } else {
            radius = width / 2;
        }
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        int width = Math.min(widthSize, heightSize);
        if (widthMode == MeasureSpec.UNSPECIFIED) {
            width = heightSize + getPaddingRight() + getPaddingLeft();
        } else if (heightMode == MeasureSpec.UNSPECIFIED) {
            width = widthSize + getPaddingRight() + getPaddingLeft();
        }
        setMeasuredDimension(width, width);
    }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • 原文地址:http://www.android100.org/html/201606/06/241682.html...
    AFinalStone阅读 866评论 0 1
  • 本笔记整理自: https://www.gitbook.com/book/tom510230/android_...
    01_小小鱼_01阅读 965评论 0 4
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,036评论 1 32
  • 一、View事件体系 1.什么是 View 和 View的位置坐标 View是什么: View 是一种界面层的控件...
    sssssss_阅读 1,248评论 0 7
  • 今年是改革开放40周年,本人因为受益于这个时代而充满感恩。最近电视台播出的电视连续剧《大江大河》引发了观众对这段历...
    德草心阅读 207评论 0 4