1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| class CircleProgressView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE strokeWidth = 10f.dp.toPx() color = Color.LTGRAY } private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE strokeWidth = 10f.dp.toPx() color = Color.GREEN strokeCap = Paint.Cap.ROUND } private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER textSize = 24f.dp.toPx() color = Color.BLACK } var progress: Int = 0 set(value) { field = value.coerceIn(0, 100) invalidate() } var progressColor: Int = Color.GREEN set(value) { field = value progressPaint.color = value invalidate() } private val rectF = RectF() override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) val padding = backgroundPaint.strokeWidth / 2 rectF.set( padding, padding, w - padding, h - padding ) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val centerX = width / 2f val centerY = height / 2f canvas.drawCircle(centerX, centerY, minOf(centerX, centerY) - backgroundPaint.strokeWidth, backgroundPaint) val sweepAngle = (progress / 100f) * 360f canvas.drawArc(rectF, -90f, sweepAngle, false, progressPaint) val text = "$progress%" val textY = centerY - (textPaint.descent() + textPaint.ascent()) / 2 canvas.drawText(text, centerX, textY, textPaint) } fun setProgressAnimated(targetProgress: Int, duration: Long = 500L) { val startProgress = progress val animator = ValueAnimator.ofInt(startProgress, targetProgress) animator.duration = duration animator.interpolator = DecelerateInterpolator() animator.addUpdateListener { animation -> progress = animation.animatedValue as Int } animator.start() } }
|