自己实现双向拖动进度条

最近一直在琢磨乱七八糟的东西,写了一个双向的拖动条,随便写着玩

QQ图片20210427132120.png

代码如下,直接引用就好了。写的很简陋,但是还是用到的一点点自定义view的知识

package com.gtxc.linedemo

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import androidx.core.util.rangeTo
import kotlin.math.abs

class LineDemo(context: Context, attributeSet: AttributeSet) : View(context, attributeSet) {
    private val paint = Paint()
    private var canvas: Canvas? = null
    private var startX = 15f;//第一个圆点
    private var startY = 15f;
    private var endX = 0f//第二个圆点
    private var endY = 15f;

    init {
        paint.color = Color.RED
        paint.strokeWidth = 8f
        paint.isAntiAlias = true

    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {//手指按下
                val mid = width/2//中间点

                if (event.x {
                val mid = width / 2//中间点

                if (event.x < mid) {
                    startX = event.x
                } else {
                    endX = event.x
                }
                drawData()
                return true
            }


        }
        return true
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        this.canvas = canvas
        canvas?.drawCircle(startX, startY, 10f, paint)
        canvas?.drawLine(
            startX,
            startY,
            if (endX == 0f) width.toFloat() - 15f else endX,
            endY,
            paint
        )
        canvas?.drawCircle(if (endX == 0f) width.toFloat() - 15f else endX, endY, 10f, paint)
        Log.i("onDraw", "endX---$endX---endY---$endY---width---$width")

        Log.i("percent","${(startX/width).toBigDecimal()}")
        Log.i("percent","${(endX/width).toBigDecimal()}")

    }

    fun drawData() {
        invalidate()
    }

    //fun init(){
//    canvas?.drawCircle(startX, startY, 10f, paint)
//    canvas?.drawLine(startX, startY, width.toFloat() - 5f, endY, paint)
//    canvas?.drawCircle(measuredWidth.toFloat() - 15f, endY, 10f, paint)
//    invalidate()
//}
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

}

你可能感兴趣的:(自己实现双向拖动进度条)