帮我用Kotlin写一个自定义的进度条,渐变色的
时间: 2023-04-10 15:02:43 浏览: 148
非常感谢您的提问,我可以为您提供以下 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 maxProgress = 100
private var progressColor = Color.BLUE
private var backgroundColor = Color.GRAY
private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG)
init {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.GradientProgressBar)
progressColor = typedArray.getColor(R.styleable.GradientProgressBar_progressColor, Color.BLUE)
backgroundColor = typedArray.getColor(R.styleable.GradientProgressBar_backgroundColor, Color.GRAY)
typedArray.recycle()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val width = width.toFloat()
val height = height.toFloat()
// Draw background
backgroundPaint.color = backgroundColor
canvas.drawRect(0f, 0f, width, height, backgroundPaint)
// Draw progress
progressPaint.shader = LinearGradient(0f, 0f, width, height, intArrayOf(Color.RED, progressColor, Color.YELLOW), null, Shader.TileMode.CLAMP)
val progressWidth = progress * width / maxProgress
canvas.drawRect(0f, 0f, progressWidth, height, progressPaint)
}
fun setProgress(progress: Int) {
this.progress = progress
invalidate()
}
fun setMaxProgress(maxProgress: Int) {
this.maxProgress = maxProgress
invalidate()
}
fun setProgressColor(progressColor: Int) {
this.progressColor = progressColor
invalidate()
}
fun setBackgroundColor(backgroundColor: Int) {
this.backgroundColor = backgroundColor
invalidate()
}
}
```
您可以在布局文件中使用以下代码来添加自定义的进度条:
```
<com.example.GradientProgressBar
android:layout_width="match_parent"
android:layout_height="10dp"
app:progressColor="#FF4081"
app:backgroundColor="#E0E0E0"/>
```
其中,`progressColor` 和 `backgroundColor` 属性可以用来设置进度条的前景色和背景色。您可以根据需要进行修改。
阅读全文