最近一直在琢磨亂七八糟的東西,寫了一個(gè)雙向的拖動(dòng)條澜沟,隨便寫著玩
代碼如下,直接引用就好了。寫的很簡(jiǎn)陋筛婉,但是還是用到的一點(diǎn)點(diǎn)自定義view的知識(shí)
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;//第一個(gè)圓點(diǎn)
private var startY = 15f;
private var endX = 0f//第二個(gè)圓點(diǎn)
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//中間點(diǎn)
if (event.x<mid){
startX=event.x
}else{
endX=event.x
}
drawData()
return true
}
MotionEvent.ACTION_MOVE -> {
val mid = width / 2//中間點(diǎn)
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)
}
}