package com.example.smart.ui.icondraw
|
|
import android.content.Context
|
import android.graphics.Canvas
|
import android.graphics.Color
|
import android.graphics.Paint
|
import android.graphics.Point
|
import android.graphics.PointF
|
import android.graphics.Rect
|
import android.graphics.RectF
|
import android.util.AttributeSet
|
import android.view.MotionEvent
|
import android.view.View
|
import com.example.basecore.util.ScreenUtil
|
import com.example.basecore.util.dp2px
|
|
/**
|
* @author: dai hang
|
* @data: 2023/12/20 14:34
|
* @description:
|
*/
|
class DrawView @JvmOverloads constructor(
|
context: Context,
|
attrs: AttributeSet? = null,
|
defStyleAttr: Int = 0,
|
) : View(context, attrs, defStyleAttr) {
|
|
companion object {
|
const val shape_none = "none"
|
const val shape_round = "round"
|
const val shape_rect = "rect"
|
}
|
|
private var list = ArrayList<RectF>()
|
private var drawingRect = RectF()
|
|
private var drawShape = shape_rect
|
|
|
private var strokeWidth = 3
|
private val paint: Paint
|
|
private var touchPoint: PointF
|
private val movePoint: PointF
|
|
init {
|
paint = Paint()
|
touchPoint = PointF()
|
movePoint = PointF()
|
|
strokeWidth = context.dp2px(3)
|
paint.strokeWidth = strokeWidth.toFloat()
|
paint.color = Color.RED
|
paint.isAntiAlias = true
|
paint.style = Paint.Style.STROKE
|
}
|
|
fun updateShape(shape: String) {
|
drawShape = shape
|
invalidate()
|
}
|
|
fun isEdit(): Boolean {
|
return list.isNotEmpty()
|
}
|
|
fun clear() {
|
drawShape = shape_none
|
drawingRect.setEmpty()
|
list.clear()
|
invalidate()
|
}
|
|
override fun onTouchEvent(event: MotionEvent?): Boolean {
|
if (drawShape == shape_none) {
|
return super.onTouchEvent(event)
|
}
|
when (event?.action) {
|
MotionEvent.ACTION_DOWN -> {
|
touchPoint.x = event.x
|
touchPoint.y = event.y
|
}
|
|
MotionEvent.ACTION_MOVE -> {
|
movePoint.x = event.x
|
movePoint.y = event.y
|
|
val startX = touchPoint.x.coerceAtMost(movePoint.x)
|
val startY = touchPoint.y.coerceAtMost(movePoint.y)
|
val endX = touchPoint.x.coerceAtLeast(movePoint.x)
|
val endY = touchPoint.y.coerceAtLeast(movePoint.y)
|
|
drawingRect.set(startX, startY, endX, endY)
|
invalidate()
|
}
|
|
MotionEvent.ACTION_UP -> {
|
list.add(RectF(drawingRect))
|
drawingRect.setEmpty()
|
invalidate()
|
}
|
}
|
return true
|
}
|
|
override fun onDraw(canvas: Canvas) {
|
super.onDraw(canvas)
|
super.onDraw(canvas)
|
for (rect in list) {
|
canvas?.drawRect(rect, paint)
|
}
|
when (drawShape) {
|
shape_rect -> {
|
if (!drawingRect.isEmpty) {
|
canvas?.drawRect(drawingRect, paint)
|
}
|
}
|
|
shape_round -> {
|
|
}
|
|
else -> {
|
|
}
|
}
|
}
|
|
// override fun onDraw(canvas: Canvas?) {
|
//
|
// }
|
}
|