Android studio实现圆形进度条

参考博客
效果图
在这里插入图片描述
MainActivity

import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TextView;import java.util.Timer;
import java.util.TimerTask;public class MainActivity extends AppCompatActivity {private CircleProgressBar progressBar;private TextView percentageTextView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);progressBar = findViewById(R.id.progressBar);percentageTextView = findViewById(R.id.percentageTextView);// 设置最大进度值为100progressBar.setProgress(100);Timer timer = new Timer();timer.scheduleAtFixedRate(new TimerTask() {int i = 0;@Overridepublic void run() {if (i <= 100) {final int progress = i;runOnUiThread(new Runnable() {@Overridepublic void run() {progressBar.setProgress(progress);percentageTextView.setText("SDC" + "\n" + progress + "%" + "\n" + "充电中");}});i++;} else {timer.cancel();}}}, 0, 50);}
}

CircleProgressBar

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.nfc.Tag;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;import androidx.annotation.Nullable;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;public class CircleProgressBar extends View {//起始角度控制半圆开口的大小,数值越小开口越大,数值越大开口越小private static final float START_ANGLE = 135f;private static final float MAX_ANGLE = 270f;private float progress = 0;private float centerX;private float centerY;private float width;private float height;private int lineWidth = dp2px(20); // 绘制圆环的线宽private int pointWidth = dp2px(2); // 绘制圆点线宽private SweepGradient sweepGradient;private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);//抗锯齿标志private Paint pointPaint = new Paint(Paint.ANTI_ALIAS_FLAG);private ObjectAnimator animator;private int[] colors = {Color.parseColor("#09F5E6"),Color.parseColor("#09F5E6"),//浅色Color.parseColor("#23F2A4"),Color.parseColor("#40EF59"),Color.parseColor("#7EED26"),Color.parseColor("#B7EC15"),Color.parseColor("#FFE300"),Color.parseColor("#FF0B00"),Color.parseColor("#FF0000"),//深色};public CircleProgressBar(Context context) {this(context, null);}public CircleProgressBar(Context context, @Nullable AttributeSet attrs) {this(context, attrs, 0);}public CircleProgressBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);paint.setColor(Color.GRAY); //设置颜色paint.setStyle(Paint.Style.STROKE);//设置画笔样式STROKE:描边;paint.setStrokeCap(Paint.Cap.ROUND);//设置圆形线帽paint.setStrokeWidth(lineWidth);//画笔的线宽度(lineWidth)pointPaint.setColor(Color.WHITE);pointPaint.setStyle(Paint.Style.STROKE);//点画笔的样式为描边(Paint.Style.STROKE)pointPaint.setStrokeWidth(pointWidth);//点画笔的线宽度(pointWidth)}public void setProgress(float progress) {this.progress = progress;invalidate();}@Overrideprotected void onSizeChanged(int w, int h, int oldw, int oldh) {super.onSizeChanged(w, h, oldw, oldh);//getWidth() 和 getHeight() 函数分别获取屏幕的宽度和高度width = getWidth();height = getHeight();//除以2来计算出屏幕中心点的坐标(centerX 和 centerY)centerX = getWidth() / 2;centerY = getHeight() / 2;//使用 SweepGradient 类创建一个扫描渐变对象,传入中心点坐标(centerX 和 centerY)、渐变颜色数组(colors)和一个可选的颜色位置数组sweepGradient = new SweepGradient(centerX, centerY, colors, null);//改变开始渐变的角度(默认从右边开始画圆渐变,旋转90度就从下方开始画圆渐变,旋转之后更好设置颜色渐变值)//创建一个 Matrix 对象并使用 setRotate() 方法将渐变旋转90度,以改变渐变的起始角度Matrix matrix = new Matrix();matrix.setRotate(90, centerX, centerY);//将渐变对象设置为画笔(paint)的着色器(shader),以实现扫描渐变效果sweepGradient.setLocalMatrix(matrix);paint.setShader(sweepGradient);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);// 绘制环形drawArc(canvas);// 绘制末尾圆点drawPoint(canvas);}private void drawArc(Canvas canvas) {int padding = lineWidth + pointWidth;canvas.drawArc(padding, padding, width - padding, height - padding, START_ANGLE, MAX_ANGLE, false, paint);/*代码作用:在指定的画布上绘制一个弧形图形,其位置和样式由参数决定使用画布(Canvas)对象绘制一个弧形(Arc)的图形。具体参数解释如下:padding:指定弧形图形的边距,即距离画布边界的距离。width:画布的宽度。height:画布的高度。START_ANGLE:弧形的起始角度,以度数表示。MAX_ANGLE:弧形的角度范围,以度数表示。false:指定是否使用中心点连接起始点和结束点,这里为false表示不连接。paint:画笔(Paint)对象,用于指定绘制弧形的样式和颜色。*/}private void drawPoint(Canvas canvas) {//绘制一个圆形进度条,并在进度条上显示进度//创建了一个 Path 对象,然后根据给定的进度计算出扫过的角度 sweepAnglePath path = new Path();float sweepAngle = (MAX_ANGLE * progress) / 100.0f;Log.e("CircleProgressBar-E", "sweepAngle = " + sweepAngle + ", progress = " + progress);//将起始点和终止点添加到 Path 对象中,形成一个圆弧int padding = lineWidth + pointWidth;path.addArc(padding, padding, width - padding, height - padding, START_ANGLE, sweepAngle);//使用 PathMeasure 对象获取圆弧上指定位置的坐标,并将其存储在 pos 数组中PathMeasure measure = new PathMeasure(path, false);float[] pos = new float[2];//通过 pos 数组中的坐标来绘制进度条上的进度标记measure.getPosTan(measure.getLength() - 1, pos, null);pointPaint.setColor(Color.parseColor("#FF7968"));pointPaint.setStyle(Paint.Style.FILL);//在画布上绘制一个圆形。它使用了pos数组中的前两个元素作为圆心的坐标,//lineWidth减去pointWidth的值作为圆的半径,pointPaint作为绘制圆的画笔。绘制的圆形将会显示在画布上canvas.drawCircle(pos[0], pos[1], lineWidth - pointWidth, pointPaint);pointPaint.setColor(Color.WHITE);pointPaint.setStyle(Paint.Style.STROKE);canvas.drawCircle(pos[0], pos[1], lineWidth - pointWidth, pointPaint);}public int dp2px(final float dpValue) {//将设备独立像素(dp)转换为像素(px)//获取系统的显示度量(Resources.getSystem().getDisplayMetrics()),其中包含了设备的屏幕密度(density)信息。// 然后,将dpValue乘以屏幕密度(scale),再乘以0.5f,并将结果转换为整数(int)返回。// 这个0.5f的作用是进行四舍五入(rounding)操作,以便在转换过程中更准确地处理小数部分。// 最终返回的值就是dpValue对应的像素(px)值final float scale = Resources.getSystem().getDisplayMetrics().density;return (int) (dpValue * scale + 0.5f);}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"android:orientation="vertical"android:background="@color/royalblue"><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal"android:layout_gravity="center"android:padding="20dp"android:layout_marginTop="10dp"android:layout_marginBottom="30dp"><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="vertical"android:layout_marginRight="60dp"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="258"android:textColor="@color/white"/><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="电压(V)"android:textColor="@color/white"/></LinearLayout><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="vertical"android:layout_marginRight="60dp"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="258"android:textColor="@color/white"/><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="电压(V)"android:textColor="@color/white"/></LinearLayout><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="vertical"android:layout_gravity="right"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="258"android:textColor="@color/white"/><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="电压(V)"android:textColor="@color/white"/></LinearLayout></LinearLayout>
<LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="vertical"android:layout_gravity="center"><com.example.halfcircleprogressbar.CircleProgressBarandroid:id="@+id/progressBar"android:layout_width="330dp"android:layout_height="330dp"android:layout_gravity="center"android:layout_centerInParent="true"tools:ignore="MissingClass,MissingConstraints" /><TextViewandroid:id="@+id/percentageTextView"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:layout_centerInParent="true"android:layout_marginTop="-150dp"android:textSize="24sp"tools:ignore="MissingConstraints"android:textColor="@color/white"/></LinearLayout></LinearLayout>

value/attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources><declare-styleable name="CircleProgressView">//背景颜色<attr name="outerColor" format="color"/>//圆弧颜色<attr name="innerColor" format="color"/>//弧宽度<attr name="borderWidth" format="dimension"/>//渐变色起始颜色<attr name="foreStartColor" format="color" />//渐变色结束颜色<attr name="foreEndColor" format="color" /></declare-styleable>
</resources>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/91901.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

AIGC:初学者使用“C知道”实现AI人脸识别

文章目录 前言人脸识别介绍准备工作创作过程生成人脸识别代码下载分类文件安装 OpenCV生成人脸识别代码&#xff08;图片&#xff09; 创作成果总结 前言 从前&#xff0c;我们依靠各种搜索引擎来获取内容&#xff0c;但随着各类数据在互联网世界的爆炸式增长&#xff0c;加上…

文献阅读:Deep Learning Enabled Semantic Communication Systems

目录 论文简介关于文章内容的总结引申出不理解的问题 论文简介 作者 Huiqiang Xie Zhijin Qin Geoffrey Ye Li Biing-Hwang Juang 发表期刊or会议 《IEEE TRANSACTIONS ON SIGNAL PROCESSING》 发表时间 2021.4 这篇论文由《Deep Learning based Semantic Communications: A…

ZooKeeper数据模型/znode节点深入

1、Znode的数据模型 1.1 Znode是什么&#xff1f; Znode维护了一个stat结构&#xff0c;这个stat包含数据变化的版本号、访问控制列表变化、还有时间戳。版本号和时间戳一起&#xff0c;可让Zookeeper验证缓存和协调更新。每次znode的数据发生了变化&#xff0c;版本号就增加。…

Ansible学习笔记9

yum_repository模块&#xff1a; yum_repository模块用于配置yum仓库的。 测试下&#xff1a; [rootlocalhost ~]# ansible group1 -m yum_repository -a "namelocal descriptionlocalyum baseurlfile:///mnt/ enabledyes gpgcheckno" 192.168.17.106 | CHANGED &g…

Unity ShaderGraph教程——基础shader

1.基本贴图shader&#xff1a; 基础贴图实现&#xff1a;主贴图、自发光贴图、光滑度贴图、自发光贴图&#xff08;自发光还加入了颜色影响和按 钮开关&#xff09;. 步骤&#xff1a;最左侧操作组——新建texture2D——新建sample texture 2D承…

pdfh5在线预览pdf文件

前言 pc浏览器和ios的浏览器都可以直接在线显示pdf文件&#xff0c;但是android浏览器不能在线预览pdf文件&#xff0c;如何预览pdf文件&#xff1f; Github: https://github.com/gjTool/pdfh5 Gitee: https://gitee.com/gjTool/pdfh5 使用pdfh5预览pdf 编写预览页面 <…

docker network

docker network create <network>docker network connect <network> <container>docker network inspect <network>使用这个地址作为host即可 TODO&#xff1a;添加docker-compose

2023年全国职业院校技能大赛信息安全管理与评估网络安全渗透任务书

全国职业院校技能大赛 高等职业教育组 信息安全管理与评估 任务书 模块三 网络安全渗透、理论技能与职业素养 比赛时间及注意事项 本阶段比赛时长为180分钟&#xff0c;时间为9:00-12:00。 【注意事项】 &#xff08;1&#xff09;通过找到正确的flag值来获取得分&#xff0c;f…

Samba服务器

目录 一、什么是Samba&#xff1f; 二、Samba进程 三、Samba主要功能 四、Samba工作流程 五、Samba安全级别 六、Sam主配置文件/etc/samba/smb.conf 七、Samba服务配置案例 一、什么是Samba&#xff1f; Samba可以让linux计算机和windows计算机之间实现文件和打印机资源共享的一…

安全开发-JS应用NodeJS指南原型链污染Express框架功能实现审计WebPack打包器第三方库JQuery安装使用安全检测

文章内容 环境搭建-NodeJS-解析安装&库安装安全问题-NodeJS-注入&RCE&原型链案例分析-NodeJS-CTF题目&源码审计打包器-WebPack-使用&安全第三方库-JQuery-使用&安全 环境搭建-NodeJS-解析安装&库安装 Node.js是运行在服务端的JavaScript 文档参考…

【Unity每日一记】WheelColider组件汽车游戏的关键

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 秩沅 原创 &#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a;uni…

设计模式-适配器

文章目录 一、简介二、适配器模式基础1. 适配器模式定义与分类2. 适配器模式的作用与优势3.UML图 三、适配器模式实现方式1. 类适配器模式2. 对象适配器模式3.类适配器模式和对象适配器模式对比 四、适配器模式应用场景1. 继承与接口的适配2. 跨平台适配 五、适配器模式与其他设…