Kotlin自定义View: CircularProgressBar实现圆形进度条
Kotlin自定义View: CircularProgressBar实现圆形进度条
本文提供了一个使用Kotlin编写的自定义View CircularProgressBar,用于在Android应用中创建圆形进度条。
代码示例
以下是CircularProgressBar类的完整代码:kotlinimport android.content.Contextimport android.graphics.*import android.util.AttributeSetimport android.view.View
class CircularProgressBar @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) {
private var progress = 0 private var backgroundColor = Color.GRAY private var progressColor = Color.BLUE private var strokeWidth = 10f
init { // 初始化属性 progress = 0 backgroundColor = Color.GRAY progressColor = Color.BLUE strokeWidth = 10f }
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { // 设置 CircularProgressBar 的尺寸 super.onMeasure(widthMeasureSpec, heightMeasureSpec) val size = measuredWidth.coerceAtMost(measuredHeight) setMeasuredDimension(size, size) }
override fun onDraw(canvas: Canvas) { // 在画布上绘制圆形背景和进度条 super.onDraw(canvas) val width = width val height = height val radius = width.coerceAtMost(height) / 2
// 绘制背景 val backgroundPaint = Paint() backgroundPaint.color = backgroundColor backgroundPaint.style = Paint.Style.FILL canvas.drawCircle((width / 2).toFloat(), (height / 2).toFloat(), radius.toFloat(), backgroundPaint)
// 绘制进度条 val progressPaint = Paint() progressPaint.color = progressColor progressPaint.style = Paint.Style.STROKE progressPaint.strokeWidth = strokeWidth progressPaint.strokeCap = Paint.Cap.ROUND val progressRect = RectF(strokeWidth, strokeWidth, (width - strokeWidth).toFloat(), (height - strokeWidth).toFloat()) val sweepAngle = 360 * progress / 100f canvas.drawArc(progressRect, -90f, sweepAngle, false, progressPaint) }
fun setProgress(progress: Int) { // 更新进度值 this.progress = progress invalidate() }}
使用方法
-
在你的布局文件中添加
CircularProgressBar:xml <your.package.name.CircularProgressBar android:id='@+id/circularProgressBar' android:layout_width='100dp' android:layout_height='100dp' /> -
在你的 Kotlin 代码中获取
CircularProgressBar实例并设置进度:kotlin val circularProgressBar = findViewById<CircularProgressBar>(R.id.circularProgressBar) circularProgressBar.setProgress(50) // 设置进度为 50%
通过调用 setProgress() 方法,你可以根据需要更新进度条的进度。
自定义属性
你可以通过自定义属性来自定义 CircularProgressBar 的外观,例如进度条的颜色、宽度等。
总结
CircularProgressBar 类提供了一个简单易用的方式来创建圆形进度条,你可以根据自己的需求进行定制和扩展。
原文地址: https://www.cveoy.top/t/topic/N7k 著作权归作者所有。请勿转载和采集!