用Kotlin帮我写一个Android自定义View进度条,进度条颜色是渐变色,宽高可以自行设置
时间: 2023-04-10 20:02:33 浏览: 160
好的,以下是用 Kotlin 编写的 Android 自定义 View 进度条的代码,进度条颜色为渐变色,宽高可以自行设置:
```kotlin
class GradientProgressBar @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private var progress = 0f
private var progressColorStart = Color.parseColor("#FF5722")
private var progressColorEnd = Color.parseColor("#FFC107")
private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val width = width.toFloat()
val height = height.toFloat()
val progressWidth = progress * width
val gradient = LinearGradient(
0f, 0f, width, 0f,
progressColorStart, progressColorEnd, Shader.TileMode.CLAMP
)
progressPaint.shader = gradient
canvas.drawRect(0f, 0f, progressWidth, height, progressPaint)
}
fun setProgressColor(startColor: Int, endColor: Int) {
progressColorStart = startColor
progressColorEnd = endColor
invalidate()
}
fun setProgress(progress: Float) {
this.progress = progress
invalidate()
}
}
```
希望这个代码对你有所帮助!