Untitled

CustomProgressBarsInCircle
 avatar
unknown
kotlin
5 years ago
2.8 kB
24
Indexable
class HalfCircleView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val darkGreenPaint = Paint().apply {
        style = Paint.Style.FILL
        isAntiAlias = true
        color = Color.parseColor("#388E3C")
    }
    private val lightGreenPaint = Paint().apply {
        style = Paint.Style.FILL
        isAntiAlias = true
        color = Color.parseColor("#81C784")
    }
    private val whitePaint = Paint().apply {
        style = Paint.Style.STROKE
        strokeWidth = 16f
        isAntiAlias = true
        color = Color.WHITE
    }
    private val leftProgressBar = Path()
    private val rightProgressBar = Path()
    private var leftIndicatorHeight = 100f
    private var rightIndicatorHeight = 100f
    private val margin = 16f
    private var leftRectF = RectF()
    private val rightRectF = RectF()
    private val circlePath = Path()
    private val leftProgressBarPath = Path()
    private val rightProgressBarPath = Path()

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val centerX = width / 2f
        val centerY = height / 2f
        val radius: Float = if (width > height) centerY - margin else centerX - margin
        val leftProgressBarHeight = leftIndicatorHeight * (height / 100)
        val rightProgressBarHeight = rightIndicatorHeight * (height / 100)

        leftRectF.apply {
            left = centerX
            right = 0f
            top = leftProgressBarHeight - margin
            bottom = height.toFloat() - margin
        }
        rightRectF.apply {
            left = centerX
            right = width.toFloat()
            top = rightProgressBarHeight - margin
            bottom = height.toFloat() - margin
        }

        circlePath.addCircle(centerX, centerY, radius, Path.Direction.CW)
        leftProgressBarPath.addRect(leftRectF, Path.Direction.CW)
        rightProgressBarPath.addRect(rightRectF, Path.Direction.CW)

        //intersecting rectangles with circle
        leftProgressBar.op(leftProgressBarPath, circlePath, Path.Op.INTERSECT)
        rightProgressBar.op(rightProgressBarPath, circlePath, Path.Op.INTERSECT)

        //drawing left & right progress indicators
        canvas.drawPath(leftProgressBar, darkGreenPaint)
        canvas.drawPath(rightProgressBar, lightGreenPaint)

        //drawing white circle with vertical line
        canvas.drawCircle(centerX, centerY, radius, whitePaint)
        canvas.drawLine(centerX, margin, centerX, height.toFloat() - margin, whitePaint);

    }

    fun setProgress(leftValue: Float, rightValue: Float) {
        leftIndicatorHeight = 100f - leftValue
        rightIndicatorHeight = 100f - rightValue
        invalidate()
    }
}
Editor is loading...