Last active
November 20, 2020 14:32
-
-
Save svinouze/6de8926a94e0c82914d238c5e8560f1b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SegmentedProgressBar @JvmOverloads constructor( | |
context: Context, | |
attrs: AttributeSet? = null, | |
defStyleAttr: Int = 0 | |
) : View(context, attrs, defStyleAttr) { | |
@get:ColorInt | |
var segmentColor: Int = Color.WHITE | |
var segmentAlpha: Float = 1f | |
var segmentCount: Int = 1 | |
var spacing: Float = 0f | |
private val segmentPaints: MutableList<Paint> = mutableListOf() | |
private val segmentPaths: MutableList<Path> = mutableListOf() | |
private val segmentCoordinatesComputer: SegmentCoordinatesComputer = SegmentCoordinatesComputer() | |
init { | |
initSegmentPaths() | |
} | |
override fun onDraw(canvas: Canvas) { | |
val w = width.toFloat() | |
val h = height.toFloat() | |
(0 until segmentCount).forEach { position -> | |
val path = segmentPaths[position] | |
val paint = segmentPaints[position] | |
val segmentCoordinates = segmentCoordinatesComputer.segmentCoordinates(position, segmentCount, w, spacing) | |
drawSegment(canvas, path, paint, segmentCoordinates, segmentColor, segmentAlpha) | |
} | |
} | |
private fun initSegmentPaths() { | |
(0 until segmentCount).forEach { _ -> | |
segmentPaths.add(Path()) | |
segmentPaints.add(Paint(Paint.ANTI_ALIAS_FLAG)) | |
} | |
} | |
private fun drawSegment(canvas: Canvas, path: Path, paint: Paint, coordinates: SegmentCoordinates, color: Int, alpha: Float) { | |
path.run { | |
reset() | |
moveTo(coordinates.topLeftX, 0f) | |
lineTo(coordinates.topRightX, 0f) | |
lineTo(coordinates.bottomRightX, height.toFloat()) | |
lineTo(coordinates.bottomLeftX, height.toFloat()) | |
close() | |
} | |
paint.color = color | |
paint.alpha = alpha.toAlphaPaint() | |
canvas.drawPath(path, paint) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment