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;

    @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>
  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Android Studio中可以使用ProgressBar控件来实现圆形进度条。具体实现方法如下: 1. 在布局文件中添加ProgressBar控件: ``` <ProgressBar android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" style="@style/Widget.AppCompat.ProgressBar" android:indeterminate="true" android:indeterminateTint="@color/colorPrimary" android:indeterminateTintMode="src_in" /> ``` 2. 在代码中获取ProgressBar控件并设置样式: ``` ProgressBar progressBar = findViewById(R.id.progressBar); progressBar.setIndeterminate(true); progressBar.getIndeterminateDrawable().setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.SRC_IN); ``` 其中,setIndeterminate(true)表示进度条为不确定模式,getIndeterminateDrawable()获取进度条的Drawable对象,setColorFilter()设置进度条颜色。 以上就是在Android Studio实现圆形进度条的方法。 ### 回答2: Android Studio是一个非常流行的开发工具,它提供了很多组件和控件,可以帮助开发人员创建出美观、实用的 Android 应用。其中一个非常常见的组件就是圆形进度条圆形进度条可以向用户传达某个任务正在进行中,同时也可以让用户感受到一定的乐趣和兴趣。 在 Android Studio 中,要实现圆形进度条,首先需要在布局文件中添加一个 ProgressBar 组件,并将 style 属性设置为@style/Widget.AppCompat.ProgressBar.Horizontal。 然后,为了将进度条变成圆形,需要将 ProgressBar 组件的 style 属性修改为@style/Widget.AppCompat.ProgressBar.Large,并将该属性的另一个属性android:indeterminateDrawable设置为@drawable/progress_indeterminate_circle,以显示圆形进度条。 要设置进度条的颜色,可以在 styles.xml 文件中设置 theme 的 colorAccent 属性。这可以通过为主题设置自定义颜色,从而影响所有进度条的颜色。 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> 除了以上基础设置,还可以对圆形进度条进行进一步的自定义。例如,可以设置进度条的宽度、指定进度条显示的进度百分比等等。在代码中,设置 progressBar 的属性都可以实现这些效果。 综上所述,圆形进度条是一种非常常见、实用的组件,它可以用于多种任务中,比如显示文件上传的进度、显示软件下载的进度等等。同时,通过自定义属性,我们还可以创造出独具特色的圆形进度条,为用户带来更好的使用体验。 ### 回答3: Android Studio是目前最常用的Android应用开发工具,开发者可以通过Android Studio实现各种功能和效果的界面设计,包括圆形进度条圆形进度条是一种可以展示进度的控件,它可以让用户清晰地了解当前的任务进展情况。下面是关于如何在Android Studio实现圆形进度条的详细介绍。 首先,在Android Studio中创建一个新的项目。然后,在布局文件中添加一个ProgressBar控件,并设置其样式为“?android:attr/progressBarStyleHorizontal”。 接下来,用以下代码获取ProgressBar控件: ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar); 接着,在代码中设置控件的最大值和当前进度值: progressBar.setMax(100); progressBar.setProgress(50); 以上代码将ProgressBar控件的最大值设置为100,当前进度值设置为50。 接着,在values文件夹下创建一个名为“progress_bar.xml”的文件。在这个文件中,设置ProgressBar控件的样式为“@style/CustomProgress”: <?xml version="1.0" encoding="utf-8"?> <resources> <style name="CustomProgress" parent="@android:style/Widget.ProgressBar.Horizontal"> <item name="android:indeterminateOnly">false</item> <item name="android:progressDrawable">@drawable/progress_bar_drawable</item> <item name="android:minHeight">20dp</item> <item name="android:maxHeight">20dp</item> </style> </resources> 在上面代码中,indeterminateOnly属性设置为false,表示ProgressBar控件是一个有确定进度的控件。progressDrawable属性值设置为一个名为“progress_bar_drawable”的可绘制资源文件,这个文件将显示ProgressBar控件的进度条。通过设置minHeight和maxHeight属性,可以设置ProgressBar控件的最小高度和最大高度。 最后,在drawable文件夹下创建一个名为“progress_bar_drawable.xml”的文件。在这个文件中,使用以下代码绘制ProgressBar控件的进度条: <?xml version="1.0" encoding="utf-8"?> <rotate xmlns:android="http://schemas.android.com/apk/res/android" android:fromDegrees="270" android:toDegrees="270"> <shape android:innerRadiusRatio="2.3" android:shape="ring" android:thickness="4dp" android:useLevel="true"> <gradient android:startColor="#B2FF59" android:centerColor="#FFFF00" android:endColor="#FF5252" android:centerY="0.5" android:type="sweep" android:useLevel="true" /> </shape> </rotate> 在上述代码中,使用了rotate标签旋转进度条,fromDegrees属性和toDegrees属性控制旋转的起点和终点,这里都设置为270度,表示从竖直上方开始旋转。shape标签设置进度条的形状为圆形。innerRadiusRatio属性设置内部圆的半径比例。thickness属性设置进度条的宽度。useLevel属性进行数值级别的限制,以保持与父控件相同的宽度和高度。gradient标签设置进度条的渐变颜色。startColor属性设置进度条的开始颜色,centerColor属性设置进度条的中间颜色,endColor属性设置进度条的结束颜色。centerY属性设置渐变的中心位置。type属性设置渐变类型为“sweep”,这是一种沿圆周的渐变颜色类型。 通过以上步骤,就可以在Android Studio实现一个漂亮的圆形进度条了!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值