Fixed canvas offset

This commit is contained in:
Alexey 2025-08-08 13:09:51 +03:00
commit 2d36517acb

View file

@ -14,6 +14,13 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.ParagraphStyle
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
@Composable
fun MapCanvas(
@ -25,13 +32,13 @@ fun MapCanvas(
) {
val offsetX = rememberSaveable { mutableFloatStateOf(0F) }
val offsetY = rememberSaveable { mutableFloatStateOf(0F) }
val textMeasurer = rememberTextMeasurer()
Canvas(
modifier = modifier.fillMaxSize()
.pointerInput(Unit) {
detectDragGestures { _, distance ->
offsetX.floatValue += distance.x
offsetY.floatValue += distance.y
offsetX.floatValue -= distance.x
offsetY.floatValue -= distance.y
}
}
) {
@ -40,8 +47,8 @@ fun MapCanvas(
size = size
)
val tileOffsetX = offsetX.floatValue.toInt() / TILE_SIZE.toInt()
val tileOffsetY = offsetY.floatValue.toInt() / TILE_SIZE.toInt()
val tileOffsetX = (offsetX.floatValue / TILE_SIZE).toInt()
val tileOffsetY = (offsetY.floatValue / TILE_SIZE).toInt()
val strippedOffsetX = offsetX.floatValue % TILE_SIZE
val strippedOffsetY = offsetY.floatValue % TILE_SIZE
@ -59,10 +66,10 @@ fun MapCanvas(
for (cellX in 0 .. gridWidth + 2) {
val tileX = tileOffsetX + cellX
val offsetX = TILE_SIZE * (cellX - 1)
val localOffsetX = TILE_SIZE * (cellX - 1)
for (cellY in 0 .. gridHeight + 2) {
val tileY = tileOffsetY + cellY
val offsetY = TILE_SIZE * (cellY - 1)
val localOffsetY = TILE_SIZE * (cellY - 1)
val bitmap = tiles.find { it.x == tileX && it.y == tileY && it.level == level }?.getBitmap()
@ -70,16 +77,29 @@ fun MapCanvas(
val imageBitmap = bitmap.asImageBitmap()
drawImage(
image = imageBitmap,
topLeft = offset + Offset(offsetX, offsetY)
topLeft = Offset(localOffsetX, localOffsetY) - offset
)
}
drawRect(
color = gridColor,
size = Size(TILE_SIZE, TILE_SIZE),
topLeft = offset + Offset(offsetX, offsetY),
topLeft = Offset(localOffsetX, localOffsetY) - offset,
style = Stroke(width = 4F)
)
drawText(
textMeasurer = textMeasurer,
text = buildAnnotatedString {
withStyle(ParagraphStyle(textAlign = TextAlign.Center)) {
withStyle(SpanStyle(color = gridColor)) {
append("x:%d, y:%d".format(tileX, tileY))
}
}
},
topLeft = Offset(localOffsetX, localOffsetY) - offset,
size = Size(TILE_SIZE, TILE_SIZE)
)
}
}
}