简体   繁体   中英

Problem trying to optimize for recomposition

I'm trying to port a rather complex Android View to Compose and I've managed to do a naive implementation by basically using a Canvas and moving the onDraw() code there. I've ran into issues when trying to optimize this to make it skip unneeded parts of the recomposition.

The view is a board for the game of GO (it would be the same for chess). I'm trying to get things such as the board's background to not redraw every time a move is made, as the background does not change. As my understanding of the docs is, if I pull the drawBackground() from the onDraw and just put it in an Image() composable, the Image() composable should not get recomposed unless its parameter (which is just the bitmap) changes. However, breakpoints show the method getting called every single time the position changes (eg the player makes a move). Am I doing something wrong? How could I take advantage of Compose here?

Code:

@Composable
fun Board(modifier: Modifier = Modifier, boardSize: Int, position: Position?, candidateMove: Point?, candidateMoveType: StoneType?, onTapMove: ((Point) -> Unit)? = null, onTapUp: ((Point) -> Unit)? = null) {
    val background: ImageBitmap = imageResource(id = R.mipmap.texture)

    Box(modifier = modifier
            .fillMaxWidth()
            .aspectRatio(1f)
    ) {
        Image(bitmap = background) // Expecting this to run only once, but gets run every time Board() gets recomposed!!!

        var width by remember { mutableStateOf(0) }
        val measurements = remember(width, boardSize) { doMeasurements(width, boardSize, drawCoordinates) }
        var lastHotTrackedPoint: Point? by remember { mutableStateOf(null) }
        Canvas(modifier = Modifier.fillMaxSize()) {
            if (measurements.width == 0) {
                return@Canvas
            }
            //... lots of draw code here
        }
    }
}

Any Jetpack Compose guru can help me understand why is it not skipping that recomposition?

Try putting Image(bitmap = background) in a separate composable function. Or moving Canvas to another function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM