Android 自定义圆弧进度条

本贴最后更新于 3055 天前,其中的信息可能已经时过境迁

挺久没写文章了,近段时间被拉过去写 JS 项目了,在做一个项目的时候,遇到一个新的需求就是空气质量,实现空气污染指数的时候,需要到一个圆弧的进度,在网上没找到合适,干脆就自己写了一个,顺便复习一下自定义 View,下面是具体的实现。

先看一下效果

这里的话我只做一个进度条,使用也很简单。圆弧外的文本是一个 textview,不是这个控件里面的,说明一下。

下面先看一下整体的代码:

import android.animation.ValueAnimator;

import android.content.Context;

import android.content.res.TypedArray;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.graphics.Rect;

import android.graphics.RectF;

import android.support.annotation.Nullable;

import android.util.AttributeSet;

import android.view.View;



public class ArcProgressBar extends View {

private static final String TAG = "ArcProgressBar";

/**

 * 圆弧的宽度

 */

private int mStrokeWidth = dp2px(8);

/**

 * 圆弧开始的角度

 */

private float mStartAngle = 135;

/**

 * 起点角度和终点角度对应的夹角大小

 */

private float mAngleSize = 270;

/**

 * 圆弧背景颜色

 */

private int mArcBgColor = Color.YELLOW;

/**

 * 最大的进度,用于计算进度与夹角的比例

 */

private float mMaxProgress = 500;

/**

 * 当前进度对应的起点角度到当前进度角度夹角的大小

 */

private float mCurrentAngleSize = 0;

/**

 * 当前进度

 */

private float mCurrentProgress = 0;

/**

 * 动画的执行时长

 */

private long mDuration = 3000;

/**

 * 进度圆弧的颜色

 */

private int mProgressColor = Color.RED;

/**

 * 第一行文本

 */

private String mFirstText = "42";

/**

 * 第一行文本的颜色

 */

private int mFirstTextColor = Color.RED;

/**

 * 第一行文本的字体大小

 */

private float mFirstTextSize = 56f;

/**

 * 第二行文本

 */

private String mSecondText = "优";

/**

 * 第二行文本的颜色

 */

private int mSecondTextColor = Color.RED;

/**

 * 第二行文本的字体大小

 */

private float mSecondTextSize = 56f;

public ArcProgressBar(Context context) {

    super(context, null);

}

public ArcProgressBar(Context context, @Nullable AttributeSet attrs) {

    super(context, attrs, 0);

}

public ArcProgressBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {

    super(context, attrs, defStyleAttr);

    initAttr(context, attrs);

}

/**

 * 设置初始化的参数

 *

 * @param context

 * @param attrs

 */

private void initAttr(Context context, AttributeSet attrs) {

    TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ArcProgressBar);

    mMaxProgress = array.getFloat(R.styleable.ArcProgressBar_arc_max_progress, 500f);

    mArcBgColor = array.getColor(R.styleable.ArcProgressBar_arc_bg_color, Color.YELLOW);

    mStrokeWidth = dp2px(array.getDimension(R.styleable.ArcProgressBar_arc_stroke_width, 12f));

    mCurrentProgress = array.getFloat(R.styleable.ArcProgressBar_arc_progress, 300f);

    mProgressColor = array.getColor(R.styleable.ArcProgressBar_arc_progress_color, Color.RED);

    mFirstText = array.getString(R.styleable.ArcProgressBar_arc_first_text);

    mFirstTextSize = dp2px(array.getDimension(R.styleable.ArcProgressBar_arc_first_text_size, 20f));

    mFirstTextColor = array.getColor(R.styleable.ArcProgressBar_arc_first_text_color, Color.RED);

    mSecondText = array.getString(R.styleable.ArcProgressBar_arc_second_text);

    mSecondTextSize = dp2px(array.getDimension(R.styleable.ArcProgressBar_arc_second_text_size, 20f));

    mSecondTextColor = array.getColor(R.styleable.ArcProgressBar_arc_second_text_color, Color.RED);

    mAngleSize = array.getFloat(R.styleable.ArcProgressBar_arc_angle_size, 270f);

    mStartAngle = array.getFloat(R.styleable.ArcProgressBar_arc_start_angle, 135f);

    array.recycle();

}

@Override

protected void onDraw(Canvas canvas) {

    super.onDraw(canvas);

    int centerX = getWidth() / 2;

    RectF rectF = new RectF();

    rectF.left = mStrokeWidth;

    rectF.top = mStrokeWidth;

    rectF.right = centerX * 2 - mStrokeWidth;

    rectF.bottom = centerX * 2 - mStrokeWidth;

    //画最外层的圆弧

    drawArcBg(canvas, rectF);

    //画进度

    drawArcProgress(canvas, rectF);

    //绘制第一级文本

    drawFirstText(canvas, centerX);

    //绘制第二级文本

    drawSecondText(canvas, centerX);

}

/**

 * 画最开始的圆弧

 *

 * @param canvas

 * @param rectF

 */

private void drawArcBg(Canvas canvas, RectF rectF) {

    Paint mPaint = new Paint();

    //画笔的填充样式,Paint.Style.FILL 填充内部;Paint.Style.FILL_AND_STROKE 填充内部和描边;Paint.Style.STROKE 描边

    mPaint.setStyle(Paint.Style.STROKE);

    //圆弧的宽度

    mPaint.setStrokeWidth(mStrokeWidth);

    //抗锯齿

    mPaint.setAntiAlias(true);

    //画笔的颜色

    mPaint.setColor(mArcBgColor);

    //画笔的样式 Paint.Cap.Round 圆形,Cap.SQUARE 方形

    mPaint.setStrokeCap(Paint.Cap.ROUND);

    //开始画圆弧

    canvas.drawArc(rectF, mStartAngle, mAngleSize, false, mPaint);

}

/**

 * 画进度的圆弧

 *

 * @param canvas

 * @param rectF

 */

private void drawArcProgress(Canvas canvas, RectF rectF) {

    Paint paint = new Paint();

    paint.setStyle(Paint.Style.STROKE);

    paint.setStrokeWidth(mStrokeWidth);

    paint.setColor(mProgressColor);

    paint.setAntiAlias(true);

    paint.setStrokeCap(Paint.Cap.ROUND);

    canvas.drawArc(rectF, mStartAngle, mCurrentAngleSize, false, paint);

}

/**

 * 绘制第一级文字

 *

 * @param canvas  画笔

 * @param centerX 位置

 */

private void drawFirstText(Canvas canvas, float centerX) {

    Paint paint = new Paint();

    paint.setAntiAlias(true);

    paint.setColor(mFirstTextColor);

    paint.setTextAlign(Paint.Align.CENTER);

    paint.setTextSize(mFirstTextSize);

    Rect firstTextBounds = new Rect();

    paint.getTextBounds(mFirstText, 0, mFirstText.length(), firstTextBounds);

    canvas.drawText(mFirstText, centerX, firstTextBounds.height() / 2 + getHeight() * 2 / 5, paint);

}

/**

 * 绘制第二级文本

 *

 * @param canvas  画笔

 * @param centerX 文本

 */

private void drawSecondText(Canvas canvas, float centerX) {

    Paint paint = new Paint();

    paint.setAntiAlias(true);

    paint.setColor(mSecondTextColor);

    paint.setTextAlign(Paint.Align.CENTER);

    paint.setTextSize(mSecondTextSize);

    Rect bounds = new Rect();

    paint.getTextBounds(mSecondText, 0, mSecondText.length(), bounds);

    canvas.drawText(mSecondText, centerX, getHeight() / 2 + bounds.height() / 2 +

            getFontHeight(mSecondText, mSecondTextSize), paint);

}

/**

 * 设置最大的进度

 *

 * @param progress

 */

public void setMaxProgress(int progress) {

    if (progress < 0) {

        throw new IllegalArgumentException("Progress value can not be less than 0 ");

    }

    mMaxProgress = progress;

}

/**

 * 设置当前进度

 *

 * @param progress

 */

public void setProgress(float progress) {

    if (progress < 0) {

        throw new IllegalArgumentException("Progress value can not be less than 0");

    }

    if (progress > mMaxProgress) {

        progress = mMaxProgress;

    }

    mCurrentProgress = progress;

    float size = mCurrentProgress / mMaxProgress;

    mCurrentAngleSize = (int) (mAngleSize * size);

    setAnimator(0, mCurrentAngleSize);

}

/**

 * 设置进度圆弧的颜色

 *

 * @param color

 */

public void setProgressColor(int color) {

    if (color == 0) {

        throw new IllegalArgumentException("Color can no be 0");

    }

    mProgressColor = color;

}

/**

 * 设置圆弧的颜色

 *

 * @param color

 */

public void setArcBgColor(int color) {

    if (color == 0) {

        throw new IllegalArgumentException("Color can no be 0");

    }

    mArcBgColor = color;

}

/**

 * 设置圆弧的宽度

 *

 * @param strokeWidth

 */

public void setStrokeWidth(int strokeWidth) {

    if (strokeWidth < 0) {

        throw new IllegalArgumentException("strokeWidth value can not be less than 0");

    }

    mStrokeWidth = dp2px(strokeWidth);

}

/**

 * 设置动画的执行时长

 *

 * @param duration

 */

public void setAnimatorDuration(long duration) {

    if (duration < 0) {

        throw new IllegalArgumentException("Duration value can not be less than 0");

    }

    mDuration = duration;

}

/**

 * 设置第一行文本

 *

 * @param text

 */

public void setFirstText(String text) {

    mFirstText = text;

}

/**

 * 设置第一行文本的颜色

 *

 * @param color

 */

public void setFirstTextColor(int color) {

    if (color <= 0) {

        throw new IllegalArgumentException("Color value can not be less than 0");

    }

    mFirstTextColor = color;

}

/**

 * 设置第一行文本的大小

 *

 * @param textSize

 */

public void setFirstTextSize(float textSize) {

    if (textSize <= 0) {

        throw new IllegalArgumentException("textSize can not be less than 0");

    }

    mFirstTextSize = textSize;

}

/**

 * 设置第二行文本

 *

 * @param text

 */

public void setSecondText(String text) {

    mSecondText = text;

}

/**

 * 设置第二行文本的颜色

 *

 * @param color

 */

public void setSecondTextColor(int color) {

    if (color == 0) {

        throw new IllegalArgumentException("Color value can not be less than 0");

    }

    mSecondTextColor = color;

}

/**

 * 设置第二行文本的大小

 *

 * @param textSize

 */

public void setSecondTextSize(float textSize) {

    if (textSize <= 0) {

        throw new IllegalArgumentException("textSize can not be less than 0");

    }

    mSecondTextSize = textSize;

}

/**

 * 设置圆弧开始的角度

 *

 * @param startAngle

 */

public void setStartAngle(int startAngle) {

    mStartAngle = startAngle;

}

/**

 * 设置圆弧的起始角度到终点角度的大小

 *

 * @param angleSize

 */

public void setAngleSize(int angleSize) {

    mAngleSize = angleSize;

}

/**

 * dp转成px

 *

 * @param dp

 * @return

 */

private int dp2px(float dp) {

    float density = getResources().getDisplayMetrics().density;

    return (int) (dp * density + 0.5f * (dp >= 0 ? 1 : -1));

}

/**

 * 设置动画

 *

 * @param start  开始位置

 * @param target 结束位置

 */

private void setAnimator(float start, float target) {

    ValueAnimator valueAnimator = ValueAnimator.ofFloat(start, target);

    valueAnimator.setDuration(mDuration);

    valueAnimator.setTarget(mCurrentAngleSize);

    valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

        @Override

        public void onAnimationUpdate(ValueAnimator valueAnimator) {

            mCurrentAngleSize = (float) valueAnimator.getAnimatedValue();

            invalidate();

        }

    });

    valueAnimator.start();

}

/**

 * 测量字体的高度

 *

 * @param textStr

 * @param fontSize

 * @return

 */

private float getFontHeight(String textStr, float fontSize) {

    Paint paint = new Paint();

    paint.setTextSize(fontSize);

    Rect bounds = new Rect();

    paint.getTextBounds(textStr, 0, textStr.length(), bounds);

    return bounds.height();

}

}

然后是具体使用控件里面的代码:

    android:id="@+id/arc"

    android:layout_width="100dp"

    android:layout_height="100dp"

    android:layout_gravity="center"/>

这里使用非常简单,跟其它控件的使用没什么区别。

里面还定义了很多直接在 xml 文件里面就可以直接设置的属性

这个自定义 View 非常简单,代码里面注释也写的很清楚了,就不做过多的介绍了,有兴趣的可以去做更多的扩展,比如,直接做成圆形或者扇形,还有这里必须要两行文本,如果项目需要,也可以直接去删除掉文本,不过需要计算一下文本的绘制位置。

有兴趣的可以去 GitHub 上面给个 Start,地址是:传送门

  • Android

    Android 是一种以 Linux 为基础的开放源码操作系统,主要使用于便携设备。2005 年由 Google 收购注资,并拉拢多家制造商组成开放手机联盟开发改良,逐渐扩展到到平板电脑及其他领域上。

    337 引用 • 324 回帖 • 4 关注
  • 进度条
    1 引用 • 1 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...

推荐标签 标签

  • CSS

    CSS(Cascading Style Sheet)“层叠样式表”是用于控制网页样式并允许将样式信息与网页内容分离的一种标记性语言。

    200 引用 • 545 回帖 • 1 关注
  • Maven

    Maven 是基于项目对象模型(POM)、通过一小段描述信息来管理项目的构建、报告和文档的软件项目管理工具。

    188 引用 • 319 回帖 • 222 关注
  • Windows

    Microsoft Windows 是美国微软公司研发的一套操作系统,它问世于 1985 年,起初仅仅是 Microsoft-DOS 模拟环境,后续的系统版本由于微软不断的更新升级,不但易用,也慢慢的成为家家户户人们最喜爱的操作系统。

    232 引用 • 484 回帖
  • 职场

    找到自己的位置,萌新烦恼少。

    127 引用 • 1708 回帖 • 1 关注
  • OnlyOffice
    4 引用 • 41 关注
  • frp

    frp 是一个可用于内网穿透的高性能的反向代理应用,支持 TCP、UDP、 HTTP 和 HTTPS 协议。

    17 引用 • 7 回帖 • 1 关注
  • 叶归
    25 引用 • 100 回帖 • 37 关注
  • Netty

    Netty 是一个基于 NIO 的客户端-服务器编程框架,使用 Netty 可以让你快速、简单地开发出一个可维护、高性能的网络应用,例如实现了某种协议的客户、服务端应用。

    49 引用 • 33 回帖 • 63 关注
  • ngrok

    ngrok 是一个反向代理,通过在公共的端点和本地运行的 Web 服务器之间建立一个安全的通道。

    7 引用 • 63 回帖 • 668 关注
  • 星云链

    星云链是一个开源公链,业内简单的将其称为区块链上的谷歌。其实它不仅仅是区块链搜索引擎,一个公链的所有功能,它基本都有,比如你可以用它来开发部署你的去中心化的 APP,你可以在上面编写智能合约,发送交易等等。3 分钟快速接入星云链 (NAS) 测试网

    3 引用 • 16 回帖
  • Spring

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    950 引用 • 1460 回帖 • 2 关注
  • TGIF

    Thank God It's Friday! 感谢老天,总算到星期五啦!

    293 引用 • 4496 回帖 • 688 关注
  • Mobi.css

    Mobi.css is a lightweight, flexible CSS framework that focus on mobile.

    1 引用 • 6 回帖 • 799 关注
  • Hibernate

    Hibernate 是一个开放源代码的对象关系映射框架,它对 JDBC 进行了非常轻量级的对象封装,使得 Java 程序员可以随心所欲的使用对象编程思维来操纵数据库。

    39 引用 • 103 回帖 • 740 关注
  • JavaScript

    JavaScript 一种动态类型、弱类型、基于原型的直译式脚本语言,内置支持类型。它的解释器被称为 JavaScript 引擎,为浏览器的一部分,广泛用于客户端的脚本语言,最早是在 HTML 网页上使用,用来给 HTML 网页增加动态功能。

    736 引用 • 1307 回帖 • 2 关注
  • 人工智能

    人工智能(Artificial Intelligence)是研究、开发用于模拟、延伸和扩展人的智能的理论、方法、技术及应用系统的一门技术科学。

    140 引用 • 407 回帖
  • WordPress

    WordPress 是一个使用 PHP 语言开发的博客平台,用户可以在支持 PHP 和 MySQL 数据库的服务器上架设自己的博客。也可以把 WordPress 当作一个内容管理系统(CMS)来使用。WordPress 是一个免费的开源项目,在 GNU 通用公共许可证(GPLv2)下授权发布。

    46 引用 • 114 回帖 • 139 关注
  • V2EX

    V2EX 是创意工作者们的社区。这里目前汇聚了超过 400,000 名主要来自互联网行业、游戏行业和媒体行业的创意工作者。V2EX 希望能够成为创意工作者们的生活和事业的一部分。

    16 引用 • 236 回帖 • 224 关注
  • jQuery

    jQuery 是一套跨浏览器的 JavaScript 库,强化 HTML 与 JavaScript 之间的操作。由 John Resig 在 2006 年 1 月的 BarCamp NYC 上释出第一个版本。全球约有 28% 的网站使用 jQuery,是非常受欢迎的 JavaScript 库。

    63 引用 • 134 回帖 • 736 关注
  • SSL

    SSL(Secure Sockets Layer 安全套接层),及其继任者传输层安全(Transport Layer Security,TLS)是为网络通信提供安全及数据完整性的一种安全协议。TLS 与 SSL 在传输层对网络连接进行加密。

    70 引用 • 193 回帖 • 404 关注
  • 支付宝

    支付宝是全球领先的独立第三方支付平台,致力于为广大用户提供安全快速的电子支付/网上支付/安全支付/手机支付体验,及转账收款/水电煤缴费/信用卡还款/AA 收款等生活服务应用。

    29 引用 • 347 回帖 • 2 关注
  • Openfire

    Openfire 是开源的、基于可拓展通讯和表示协议 (XMPP)、采用 Java 编程语言开发的实时协作服务器。Openfire 的效率很高,单台服务器可支持上万并发用户。

    6 引用 • 7 回帖 • 133 关注
  • Wide

    Wide 是一款基于 Web 的 Go 语言 IDE。通过浏览器就可以进行 Go 开发,并有代码自动完成、查看表达式、编译反馈、Lint、实时结果输出等功能。

    欢迎访问我们运维的实例: https://wide.b3log.org

    30 引用 • 218 回帖 • 664 关注
  • 游戏

    沉迷游戏伤身,强撸灰飞烟灭。

    188 引用 • 833 回帖 • 1 关注
  • Node.js

    Node.js 是一个基于 Chrome JavaScript 运行时建立的平台, 用于方便地搭建响应速度快、易于扩展的网络应用。Node.js 使用事件驱动, 非阻塞 I/O 模型而得以轻量和高效。

    139 引用 • 269 回帖 • 1 关注
  • OpenResty

    OpenResty 是一个基于 NGINX 与 Lua 的高性能 Web 平台,其内部集成了大量精良的 Lua 库、第三方模块以及大多数的依赖项。用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关。

    17 引用 • 51 关注
  • BAE

    百度应用引擎(Baidu App Engine)提供了 PHP、Java、Python 的执行环境,以及云存储、消息服务、云数据库等全面的云服务。它可以让开发者实现自动地部署和管理应用,并且提供动态扩容和负载均衡的运行环境,让开发者不用考虑高成本的运维工作,只需专注于业务逻辑,大大降低了开发者学习和迁移的成本。

    19 引用 • 75 回帖 • 702 关注