我知道我可以用
CircularProgressIndicator
来表示一些进展,但我也可以给它一个像这样的自定义形状:
目标将是一个半圆,其中有一些遗漏的元素,但仍然可以正确填充。我想我需要为“100%”进度部分编写一些自定义视图,但是如何为此获取自定义绘图?
您可以使用它作为自定义视图的起点。 根据要求,您可以修改这些值以获得所需的 UI。
class MyCircularProgressView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0,
) : View(context, attrs, defStyle) {
private var stroke = 25F
var size: Int = 200
set(value) {
field = value
stroke = value * 0.125F
invalidate()
}
var backgroundStartAngle: Float = 30F
set(value) {
field = value
invalidate()
}
var backgroundSweepAngle: Float = 300F
set(value) {
field = value
invalidate()
}
var progressStartAngle: Float = 150F
set(value) {
field = value
invalidate()
}
var progressSweepAngle: Float = 180F
set(value) {
field = value
invalidate()
}
private val backgroundPaint = Paint()
private val progressPaint = Paint()
init {
context.theme.obtainStyledAttributes(attrs, R.styleable.MyCircularProgressView, 0, 0).apply {
try {
// Handle attributes passed from XMl here
} finally {
recycle()
}
}
backgroundPaint.apply {
color = 0xFFE0E0E0.toInt()
strokeCap = Paint.Cap.ROUND
style = Paint.Style.STROKE
strokeWidth = stroke
}
progressPaint.apply {
color = 0xFF0000EE.toInt()
strokeCap = Paint.Cap.ROUND
style = Paint.Style.STROKE
strokeWidth = stroke
}
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawArc(
stroke / 2F,
stroke / 2F,
size.toFloat(),
size.toFloat(),
backgroundStartAngle % 360F,
backgroundSweepAngle % 360F,
false,
backgroundPaint,
)
canvas.drawArc(
stroke / 2F,
stroke / 2F,
size.toFloat(),
size.toFloat(),
progressStartAngle % 360F,
progressSweepAngle % 360F,
false,
progressPaint,
)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
setMeasuredDimension(size + stroke.toInt(), size + stroke.toInt())
}
}
输出UI