帮我用Kotlin写一个自定义的进度条,进度条的颜色是渐变色,可以通过代码设置
时间: 2023-04-10 20:02:44 浏览: 168
好的,以下是使用 Kotlin 编写自定义渐变色进度条的代码:
```kotlin
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
class GradientProgressBar(context: Context, attrs: AttributeSet) : View(context, attrs) {
private var progress = 0
private var max = 100
private var progressColor = intArrayOf(Color.RED, Color.YELLOW, Color.GREEN)
private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.GRAY
}
private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// 绘制背景
canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), backgroundPaint)
// 绘制进度条
val progressWidth = progress * width / max.toFloat()
val progressRect = RectF(0f, 0f, progressWidth, height.toFloat())
val gradient = LinearGradient(
0f, 0f, width.toFloat(), 0f,
progressColor, null, Shader.TileMode.CLAMP
)
progressPaint.shader = gradient
canvas.drawRect(progressRect, progressPaint)
}
fun setProgress(progress: Int) {
this.progress = progress
invalidate()
}
fun setMax(max: Int) {
this.max = max
invalidate()
}
fun setProgressColor(colors: IntArray) {
this.progressColor = colors
invalidate()
}
}
```
你可以在代码中设置进度条的颜色,使用 `setProgressColor` 方法即可。
阅读全文