loloof64
11/23/2020, 6:17 PMimport android.graphics.Typeface
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.preferredSize
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.unit.dp
import androidx.ui.tooling.preview.Preview
import java.util.*
@Composable
fun StaticChessBoard(modifier: Modifier = Modifier) {
val backgroundColor = Color(0xCAD63B60)
val whiteCellColor = Color(0xFFFFCE9E)
val blackCellColor = Color(0XFFD18B47)
Canvas(modifier = modifier) {
val cellsWidth = (size.width / 9.0).toFloat()
val cellsHeight = (size.height / 9.0).toFloat()
val minSize = if (cellsWidth < cellsHeight) cellsWidth else cellsHeight
val paint = Paint().asFrameworkPaint().apply {
isAntiAlias = true
textSize = (minSize * 0.4).toFloat()
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
style = android.graphics.Paint.Style.FILL
color = android.graphics.Color.parseColor("#ffcc00")
}
// background
drawRect(backgroundColor, topLeft = Offset.Zero)
// cells
(0 until 8).forEach{rowIndex ->
(0 until 8).forEach {colIndex ->
val isWhiteCell = (rowIndex+colIndex) %2 == 0
val cellColor = if (isWhiteCell) whiteCellColor else blackCellColor
val x = (cellsWidth * (0.5 + colIndex)).toFloat()
val y = (cellsHeight * (0.5 + rowIndex)).toFloat()
drawRect(cellColor, topLeft = Offset(x, y), size = Size(cellsWidth, cellsHeight))
}
}
// coordinates
drawIntoCanvas { canvas ->
(0 until 8).forEach { col ->
val text = arrayOf("A", "B", "C", "D", "E", "F", "G", "H")[col]
val x = cellsWidth * (0.88 + col).toFloat()
val y1 = (cellsHeight * 0.4).toFloat()
val y2 = (cellsHeight * 8.9).toFloat()
canvas.nativeCanvas.drawText(text, x, y1, paint)
canvas.nativeCanvas.drawText(text, x, y2, paint)
}
(0 until 8).forEach { row ->
val text = arrayOf("8", "7", "6", "5", "4", "3", "2", "1")[row]
val y = cellsHeight * (1.15 + row).toFloat()
val x1 = (cellsWidth * 0.15).toFloat()
val x2 = (cellsWidth * 8.65).toFloat()
canvas.nativeCanvas.drawText(text, x1, y, paint)
canvas.nativeCanvas.drawText(text, x2, y, paint)
}
}
}
}
And here the main scaffold where I use it