Android环形渐变进度条:如何增粗圆环并设置圆角?
解决环形进度条的加粗和圆角问题
针对你遇到的两个问题,我来一步步帮你实现想要的效果:
一、让圆环更粗
你当前使用的android:thicknessRatio="25.0"是圆环厚度与控件宽度的比例,数值越小,圆环越粗。更推荐用固定厚度值来控制,效果更直观可控:
修改shape_ring_gradient.xml中的属性:
<!-- 替换 thicknessRatio 为固定厚度,比如20dp --> android:thickness="20dp" <!-- 保留 innerRadiusRatio 或换成固定值 android:innerRadius="80dp" 都可以 --> android:innerRadiusRatio="2.17391304"
如果坚持用比例,把thicknessRatio改成8这类更小的数值,也能让圆环明显变粗。
二、给圆环添加圆角
默认的ring形状无法直接通过gradient实现圆角,推荐用VectorDrawable方案,它原生支持strokeLineCap="round"让圆环两端呈现圆角,同时能完美适配渐变效果:
步骤1:创建VectorDrawable文件
在res/drawable下新建progress_ring_vector.xml:
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="200dp" android:height="200dp" android:viewportWidth="200" android:viewportHeight="200"> <!-- 背景灰色圆环 --> <path android:pathData="M100,100 m-80,0 a80,80 0 1,1 160,0 a80,80 0 1,1 -160,0" android:strokeWidth="20" <!-- 和你设置的圆环厚度一致 --> android:strokeColor="#E0E0E0" android:fillColor="@android:color/transparent" android:strokeLineCap="round"/> <!-- 渐变进度圆环 --> <path android:pathData="M100,100 m-80,0 a80,80 0 1,1 160,0 a80,80 0 1,1 -160,0" android:strokeWidth="20" android:strokeDrawable="@drawable/progress_gradient" <!-- 引用渐变样式 --> android:fillColor="@android:color/transparent" android:strokeLineCap="round" android:trimPathStart="0"/> </vector>
步骤2:创建渐变颜色文件
在res/drawable下新建progress_gradient.xml:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <gradient android:startColor="#EB288B" android:endColor="#FE000A" android:type="linear" android:angle="180"/> </shape>
步骤3:修改ProgressBar的XML配置
替换progressDrawable为上面的VectorDrawable,同时移除旋转属性(VectorDrawable的path已经是环形,无需额外旋转):
<ProgressBar android:id="@+id/progress_bar" android:layout_width="200dp" android:layout_height="200dp" android:layout_centerInParent="true" android:layout_margin="2dp" android:indeterminate="false" android:max="100" android:progress="0" android:progressDrawable="@drawable/progress_ring_vector" android:visibility="visible"/>
步骤4:Java代码中动态设置进度
通过修改VectorDrawable的trimPathEnd来控制进度(进度值除以100得到比例):
ProgressBar progressBar = getView().findViewById(R.id.progress_bar); float progressPercent = 82 / 100f; // 对应82%的进度 // 获取VectorDrawable并更新进度 if (progressBar.getProgressDrawable() instanceof VectorDrawableCompat) { VectorDrawableCompat vectorDrawable = (VectorDrawableCompat) progressBar.getProgressDrawable(); // 第二个参数是进度path的索引(vector中第二个path,索引为1) vectorDrawable.setTrimPathEnd(progressPercent, 1); }
兼容说明
strokeDrawable属性需要Android API 24及以上支持,如果要兼容更低版本,可以考虑使用自定义View或者成熟的第三方库(比如CircleProgressView)。
内容的提问来源于stack exchange,提问作者Rob
相关产品推荐
相关产品推荐

