Android studio实现圆形进度条

参考博客
效果图
Android studio实现圆形进度条_第1张图片
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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        progressBar = findViewById(R.id.progressBar);
        percentageTextView = findViewById(R.id.percentageTextView);
        // 设置最大进度值为100
     progressBar.setProgress(100);
     
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            int i = 0;
            @Override
            public void run() {
                if (i <= 100) {
                    final int progress = i;
                    runOnUiThread(new Runnable() {
                        @Override
                        public 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();
    }
    @Override
    protected 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);
    }

    @Override
    protected 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 对象,然后根据给定的进度计算出扫过的角度 sweepAngle
        Path 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">
    <LinearLayout
        android: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">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginRight="60dp"
        >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="258"
        android:textColor="@color/white"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="电压(V)"
        android:textColor="@color/white"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginRight="60dp">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="258"
        android:textColor="@color/white"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="电压(V)"
        android:textColor="@color/white"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="right">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="258"
            android:textColor="@color/white"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="电压(V)"
            android:textColor="@color/white"/>

    </LinearLayout>
    </LinearLayout>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_gravity="center">

    <com.example.halfcircleprogressbar.CircleProgressBar
        android:id="@+id/progressBar"
        android:layout_width="330dp"
        android:layout_height="330dp"
        android:layout_gravity="center"
        android:layout_centerInParent="true"
        tools:ignore="MissingClass,MissingConstraints" />

    <TextView
        android: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>

你可能感兴趣的:(android,studio,ui)