withTransform

Function

Common
inline fun DrawScope.withTransform(
    transformBlock: DrawTransform.() -> Unit,
    drawBlock: DrawScope.() -> Unit,
) =
    with(drawContext) {
        val previousSize = size
        canvas.save()
        try {
            transformBlock(transform)
            drawBlock()
        } finally {
            canvas.restore()
            size = previousSize
        }
    }

Perform 1 or more transformations and execute drawing commands with the specified transformations applied. After this call is complete, the transformation before this call was made is restored

Parameters

transformBlockCallback invoked to issue transformations to be made before the drawing operations are issued
drawBlockCallback invoked to issue drawing operations after the transformations are applied

Code Examples

DrawScopeBatchedTransformSample

@Composable
fun DrawScopeBatchedTransformSample() {
    Canvas(Modifier.size(120.dp)) { // CanvasScope
        inset(20.0f) {
            // Use withTransform to batch multiple transformations for 1 or more drawing calls
            // that are to be drawn.
            // This is more efficient than issuing nested translation, rotation and scaling
            // calls as the internal state is saved once before and after instead of multiple
            // times between each transformation if done individually
            withTransform({
                translate(10.0f, 12.0f)
                rotate(45.0f, center)
                scale(2.0f, 0.5f)
            }) {
                drawRect(Color.Cyan)
                drawCircle(Color.Blue)
            }
            drawRect(Color.Red, alpha = 0.25f)
        }
    }
}