class ProgressView @JvmOverloads constructor(
context: Context, @Nullable attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : View(context, attrs, defStyleAttr, defStyleRes) {
private val paint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val radius: Float = dp2px(150F)
private val startAngle: Float = 270F
private val sweepAngle: Float = 180F
private val text: String = "abab"
private val textBounds: Rect = Rect()
init {
paint.textSize = dp2px(90F)
paint.textAlign = Paint.Align.CENTER
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawLine(width / 2F - radius, height / 2F, width / 2F + radius, height / 2F, paint)
paint.strokeWidth = dp2px(10F)
paint.style = Paint.Style.STROKE
paint.color = Color.BLACK
canvas.drawCircle(width / 2F, height / 2F, radius, paint)
paint.color = Color.RED
paint.strokeCap = Paint.Cap.ROUND
canvas.drawArc(
width / 2F - radius,
height / 2 - radius,
width / 2 + radius,
height / 2 + radius,
startAngle,
sweepAngle,
false,
paint
)
paint.color = Color.BLUE
paint.style = Paint.Style.FILL
// 用于固定文字
// paint.getTextBounds(text, 0, text.length, textBounds)
// val offset: Int = (textBounds.bottom + textBounds.top) / 2
// canvas.drawText(text, width / 2F, height / 2F - offset, paint)
// 用于动态文字
val fontMetrics: Paint.FontMetrics = paint.fontMetrics
val offset: Float = (fontMetrics.descent + fontMetrics.ascent) / 2
canvas.drawText(text, width / 2F, height / 2F - offset, paint)
}
private fun dp2px(dp: Float) = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp,
Resources.getSystem().displayMetrics
)
}