Klaas Kabini
05/26/2021, 12:12 PMKlaas Kabini
05/26/2021, 12:12 PMclass SteppedSeekBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatSeekBar(context, attrs, defStyleAttr) {
    //private val tickCount: Int
    private val tickTextColor: Int
    private val tickTextAccentColor: Int
    private val tickTextSize: Int
    private val tickTextPaint: Paint
    private val tickLabels: Array<String>
    private val textRect: Rect
    private val tickTextPaddingTop: Int
    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SteppedSeekBar)
        //tickCount = typedArray.getInteger(R.styleable.SteppedSeekBar_attribute_step_count, 0)
        tickTextColor = typedArray.getColor(R.styleable.SteppedSeekBar_attribute_tick_text_color, Color.BLACK)
        tickTextAccentColor = typedArray.getColor(R.styleable.SteppedSeekBar_attribute_tick_text_accent_color, Color.RED)
        tickTextSize = typedArray.getDimensionPixelSize(R.styleable.SteppedSeekBar_attribute_tick_text_size, 0)
        tickTextPaddingTop = typedArray.getDimensionPixelSize(R.styleable.SteppedSeekBar_attribute_tick_text_padding_top, 0)
        typedArray.recycle()
        tickTextPaint = Paint()
        tickTextPaint.style = Paint.Style.FILL
        tickTextPaint.color = Color.BLACK
        tickTextPaint.isAntiAlias = true
        //tickTextPaint.textSize = tickTextSize.toFloat()
        tickTextPaint.textAlign = Paint.Align.CENTER
        textRect = Rect()
        tickLabels = Array(max + 1) { "${it * 20}" }
    }
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        drawTicksLabels(canvas)
    }
    private fun drawTicksLabels(canvas: Canvas) {
        val count = max
        if (count > 1) {
            val yTop = top + height + tickTextPaddingTop.toFloat()
            val textSpace = (width - paddingStart - paddingEnd) / count.toFloat()
            canvas.save()
            tickLabels.forEachIndexed { index, tickLabel ->
                val xLeft = left + index * textSpace
                canvas.translate(xLeft, yTop)
                canvas.drawText(tickLabel, 0f, 0f, tickTextPaint)
            }
            canvas.restore()
        }
    }
}