用Kotlin帮我写一个Android自定义View进度条,进度条颜色是渐变色,宽高可以自行设置
时间: 2023-04-10 22:02:34 浏览: 106
好的,以下是用 Kotlin 编写的 Android 自定义 View 进度条的代码,进度条颜色为渐变色,宽高可以自行设置:
```
class GradientProgressBar(context: Context, attrs: AttributeSet) : View(context, attrs) {
private var progress = 0f
private var barWidth = 0f
private var barHeight = 0f
private var gradientColors = intArrayOf(Color.RED, Color.YELLOW, Color.GREEN)
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val rectF = RectF()
init {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.GradientProgressBar)
barWidth = typedArray.getDimension(R.styleable.GradientProgressBar_barWidth, 0f)
barHeight = typedArray.getDimension(R.styleable.GradientProgressBar_barHeight, 0f)
gradientColors = typedArray.getIntArray(R.styleable.GradientProgressBar_gradientColors) ?: gradientColors
typedArray.recycle()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
paint.shader = LinearGradient(0f, 0f, width.toFloat(), 0f, gradientColors, null, Shader.TileMode.CLAMP)
rectF.set(0f, 0f, progress / 100 * width, barHeight)
canvas.drawRoundRect(rectF, barHeight / 2, barHeight / 2, paint)
}
fun setProgress(progress: Float) {
this.progress = progress
invalidate()
}
}
```
注意:该代码仅供参考,可能需要根据实际需求进行修改和优化。
阅读全文