有很多跟随手指绘制线的demo,但是绘制有透明度的特别少,而且简单使用drawLine会导致出现绘制重叠的小圆球,以下的方案可以完美的实现绘制有透明度的线
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.chivi.picstoart.utils.Utils
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import kotlin.collections.ArrayList
class DrawImageView : androidx.appcompat.widget.AppCompatImageView {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
private val paint = Paint()
init {
paint.color = Color.parseColor("#6E99E1")
paint.strokeWidth = 40f
paint.isAntiAlias = true
paint.strokeCap = Paint.Cap.ROUND
paint.strokeJoin = Paint.Join.ROUND
paint.style = Paint.Style.STROKE
paint.alpha = 180
}
//删除掉的线
private val pathDel = ArrayList<Path>()
//正在画的线
private var paintSizes = ArrayList<Int>()
private val curPaths = ArrayList<Path>()
private lateinit var curPath: Path
private var lastX = 0f
private var lastY = 0f
override fun onTouchEvent(event: MotionEvent): Boolean {
//获取当前坐标
val x = event.x
val y = event.y
when (event.action) {
MotionEvent.ACTION_DOWN -> {
paintSizes.add(paint.strokeWidth.toInt())
curPath = Path()
curPaths.add(curPath)
lastX = x
lastY = y
curPath.moveTo(x, y)
}
MotionEvent.ACTION_MOVE -> {
curPath.quadTo(lastX, lastY, (x + lastX) / 2, (y + lastY) / 2)
lastX = x
lastY = y
postInvalidate()
}
MotionEvent.ACTION_UP -> {
}
}
return true
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
drawPath(canvas, paint, curPaths)
}
private fun drawPath(canvas: Canvas?, paint: Paint, drawPath: ArrayList<Path>) {
val paint1 = Paint(paint)
drawPath.forEachIndexed { index, path ->
paint1.strokeWidth = paintSizes[index].toFloat()
canvas?.drawPath(path, paint1)
}
}
//上一步
fun pre(): Boolean {
if (curPaths.size > 0) {
pathDel.add(curPaths[curPaths.size - 1])
curPaths.removeAt(curPaths.size - 1)
invalidate()
return true
}
return false
}
//下一步
fun next(): Boolean {
if (pathDel.size > 0) {
curPaths.add(pathDel[pathDel.size - 1])
pathDel.removeAt(pathDel.size - 1)
invalidate()
return true
}
return false
}
//清除所有的划线
fun clearLine() {
curPaths.clear()
pathDel.clear()
invalidate()
}
//设置线的宽度
fun setPaintSize(size: Int) {
paint.strokeWidth = size.toFloat()
}
//获取线的宽度
fun getPaintSize(): Int {
return paint.strokeWidth.toInt()
}
}