简体   繁体   English

尝试优化重组的问题

[英]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.我正在尝试将一个相当复杂的 Android 视图移植到 Compose 中,并且通过基本上使用 Canvas 并将 onDraw() 代码移到那里,我已经成功地完成了一个简单的实现。 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).该视图是 GO 游戏的棋盘(国际象棋也是如此)。 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.正如我对文档的理解,如果我从 onDraw 中提取drawBackground()并将其放入Image()可组合项中,则Image()可组合项不应重新组合,除非其参数(只是位图)发生更改。 However, breakpoints show the method getting called every single time the position changes (eg the player makes a move).但是,断点显示每次 position 更改(例如玩家移动)时都会调用该方法。 Am I doing something wrong?难道我做错了什么? How could I take advantage of Compose here?我怎么能在这里利用 Compose?

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?任何 Jetpack Compose 大师都可以帮助我理解为什么它不跳过该重组?

Try putting Image(bitmap = background) in a separate composable function.尝试将Image(bitmap = background)放在单独的可组合 function 中。 Or moving Canvas to another function.或者将Canvas移动到另一个 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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