前语
上一篇文章用贝塞尔曲线画了一个看起来不错的小红点功用,技术上没什么难度,首要便是数学上的核算。这篇文章也差不多,仿照了一个常用的滑动解锁的九宫格控件。
需求
用过安卓的都知道,用过苹果的也知道,这儿便是一个滑动解锁的控件。中心思想如下:
- 1、摆放九个圆,当手指经过圆邻近的时分选取该点,手指移动的时分将选中点连线
- 2、预设一个正确的连线,当手指抬起时的连线与预设连线一致,验证经过
- 3、经过layout参数能够设置圆和线的色彩
效果图
这儿功用牵强能够吧,感觉选中点的时分不是很流通。
代码
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.silencefly96.module_common.R
import java.util.*
import kotlin.math.sqrt
/**
* 九宫格控件
*
* @author silence
* @date 2022-11-09
*/
class PatternLockView @JvmOverloads constructor(
context: Context,
attributeSet: AttributeSet? = null,
defStyleAttr: Int = 0
): View(context, attributeSet, defStyleAttr){
/**
* 预设值
*/
var preData = LinkedList<Int>()
/**
* 回调接口
*/
var listener: OnMoveUpListener? = null
// 当前值
private var curData = LinkedList<Int>()
// 圆的色彩
private val mCircleColor: Int
// 线的色彩
private val mLineColor: Int
// 圆半径占最短宽高的份额
private val mRadiusPercent: Float
// 两点之间的间隔
private var mBetweenLength = 0f
// 第一个圆地点位置
private var mStartX = 0f
private var mStartY = 0f
// 圆半径
private var mRadius = 0f
// 当前手指地点的位置
private var mCurPosX = 0f
private var mCurPosY = 0f
// 是否在移动的状况
private var isMoving = false
// 途径
private var mPath = Path()
// 校验成果, -1失利,0未验证,1验证成功,依据验证成果修改线条色彩
private var mCheckResult = 0
// 画笔
private val mPaint = Paint().apply {
strokeWidth = 5f
style = Paint.Style.STROKE
flags = Paint.ANTI_ALIAS_FLAG
// 连接处样式: 平斜接
strokeJoin = Paint.Join.MITER
strokeMiter = 4f
// 落笔和结束时那点(point)的样式: 增加半圆
strokeCap = Paint.Cap.ROUND
}
init {
// 获取布局参数
val typedArray =
context.obtainStyledAttributes(attributeSet, R.styleable.PatternLockView)
mCircleColor = typedArray.getColor(R.styleable.PatternLockView_circleColor,
Color.LTGRAY)
mLineColor = typedArray.getColor(R.styleable.PatternLockView_lineColor, Color.YELLOW)
mRadiusPercent = typedArray.getFraction(R.styleable.PatternLockView_circleRadiusPercent,
1, 1, 0.05f)
typedArray.recycle()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val width = getDefaultSize(100, widthMeasureSpec)
val height = getDefaultSize(100, heightMeasureSpec)
// 设置参数
mBetweenLength = (if (width < height) width else height) * 0.25f
mRadius = (if (width < height) width else height) * mRadiusPercent
mStartX = width / 2f - mBetweenLength
mStartY = height / 2f - mBetweenLength
setMeasuredDimension(width, height)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when(event.action) {
MotionEvent.ACTION_DOWN -> {
// 铲除旧数据
isMoving = true
curData.clear()
mCheckResult = 0
invalidate()
}
MotionEvent.ACTION_MOVE -> {
// 判别是否进入哪个点的范围
val index = getEventCircleIndex(event.x, event.y)
if (index != -1 && !curData.contains(index)) {
curData.add(index)
}
mCurPosX = event.x
mCurPosY = event.y
// 触发制作
invalidate()
}
MotionEvent.ACTION_UP -> {
isMoving = false
// 判别是否契合设置的值
if (curData == preData) {
mCheckResult = 1
listener?.onMoveUp(true)
}else {
// 没有连线不触发判别
if (curData.size > 1) {
mCheckResult = -1
listener?.onMoveUp(false)
}
}
// 最终更新下,把移动的那部分线条去掉
invalidate()
}
}
return true
}
private fun getEventCircleIndex(x: Float, y: Float): Int {
var curX: Float
var curY: Float
for (i in 0 until 9) {
curX = mStartX + mBetweenLength * (i % 3)
curY = mStartY + mBetweenLength * (i / 3)
if (getDistance(curX, curY, x, y) <= mRadius) {
return i
}
}
return -1
}
private fun getDistance(x1: Float, y1: Float, x2: Float, y2: Float): Float {
// 平方和公式
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
return sqrt((Math.pow((x1 - x2).toDouble(), 2.0)
+ Math.pow((y1 - y2).toDouble(), 2.0)).toFloat())
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// 先制作九个点
var curX: Float
var curY: Float
mPaint.color = mCircleColor
mPaint.style = Paint.Style.FILL
mPaint.strokeWidth = 5f
for (i in 0 until 9) {
curX = mStartX + mBetweenLength * (i % 3)
curY = mStartY + mBetweenLength * (i / 3)
canvas.drawCircle(curX, curY, mRadius, mPaint)
}
// 再制作线,先画固定的线,再画移动中的线
mPaint.color = when(mCheckResult) {
-1 -> Color.RED
1 -> Color.GREEN
else -> mLineColor
}
mPaint.style = Paint.Style.STROKE
mPaint.strokeWidth = mRadius / 3f
mPath.reset()
for (i in curData) {
// 当前点坐标
curX = mStartX + mBetweenLength * (i % 3)
curY = mStartY + mBetweenLength * (i / 3)
if (curData.indexOf(i) == 0) {
mPath.moveTo(curX, curY)
}else {
mPath.lineTo(curX, curY)
}
}
// 再画最终一点
if (curData.size > 0 && isMoving) {
mPath.lineTo(mCurPosX, mCurPosY)
}
canvas.drawPath(mPath, mPaint)
}
interface OnMoveUpListener{
fun onMoveUp(success: Boolean)
}
}
对应的style文件: pattern_lock_view_style.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="PatternLockView">
<attr name="circleColor" format="color"/>
<attr name="lineColor" format="color"/>
<attr name="circleRadiusPercent" format="fraction"/>
</declare-styleable>
</resources>
首要问题
实际上,这儿没什么有难度的地方,便是画了九个圆,加上几段依据触发的点构成的连线,就不多写了,能够看代码注释。