kotlin写 安卓一个基本的成语棋盘view

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,
)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值