package com.example.custimizeview
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
class Board : View {
private val wordArray = arrayOf(
WordD(0, 3, "我", 1),
WordD(1, 3, "天", 0),
WordD(2, 3, "道", 1),
WordD(3, 3, "酬", 2),
WordD(4, 3, "勤", 3),
WordD(5, 3, "人", 1)
)
val paddingXY by lazy {
dpToPx(context, 4f).toFloat()
}
val blockInnerPadding by lazy {
dpToPx(context, 1f)
}
private val mPaintBackground = Paint(Paint.ANTI_ALIAS_FLAG).also {
it.color = Color.parseColor("#1AE61A43")
}
private val mPaintNormal = Paint(Paint.ANTI_ALIAS_FLAG).also {
it.color = Color.parseColor("#836F63")
it.isAntiAlias = true
it.strokeWidth = 2f
it.textSize = 50f
}
companion object {
const val BLOCK_N = 6
const val NORMAL_STATUS = 0
const val CORRECT_STATUS = 1
const val ERROR_STATUS = 2
const val SELECTED_STATUS = 3
}
constructor(cxt: Context) : super(cxt) {
}
constructor(cxt: Context, attrs: AttributeSet) : super(cxt, attrs) {
}
private val BLOCK_WIDTH get() = width.toFloat() / BLOCK_N
private val BLOCK_HEIGHT get() = height.toFloat() / BLOCK_N
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawRoundRect(0f, 0f, width.toFloat(), height.toFloat(), 12f, 12f, mPaintBackground)
wordArray.forEach {
when (it.status) {
NORMAL_STATUS -> mPaintNormal.color = Color.parseColor("#836F63")
CORRECT_STATUS -> mPaintNormal.color = Color.GREEN
ERROR_STATUS -> mPaintNormal.color = Color.RED
SELECTED_STATUS -> mPaintNormal.color = Color.GRAY
}
canvas?.drawText(it.text, it.col * BLOCK_WIDTH, it.row * BLOCK_HEIGHT, mPaintNormal)
}
}
}
fun dpToPx(context: Context, fDpValue: Float): Int {
val scale = context.resources.displayMetrics.density
return (fDpValue * scale + 0.5f).toInt()
}
data class WordD(
var col: Int = 0,
var row: Int = 0,
var text: String = "",
var status: Int = 0,
)
kotlin写 安卓一个基本的成语棋盘view
最新推荐文章于 2024-08-05 19:30:53 发布