Disegna un tratto

Per aiutarti a creare tratti in modo idiomatico con Compose, l'API Ink fornisce moduli di interoperabilità di Compose per la creazione, il pennello e la geometria.

Per disegnare un tratto in Compose, utilizza il componibile InProgressStrokes che richiede un'istanza di pennello predefinita, un modo per sostituire il pennello predefinito e un callback che gestisce i tratti completati.

  1. Configurare il componente UI

    InProgressStrokes(
      defaultBrush = currentBrush,
      nextBrush = onGetNextBrush,
      onStrokesFinished = onStrokesFinished,
    )
    
  2. Gestire i tratti completati

    Quando i tratti bagnati si asciugano, vengono passati all'applicazione tramite l'argomento di callback onStrokesFinished di InProgressStrokes.

    La tua app deve passare i tratti completati a un altro elemento componibile all'interno dello stesso thread UI per eseguirli sullo schermo.

    @Composable
    fun DrawingScreen(
      finishedStrokes: List<Strokes>,
      onStrokesFinished: (List<Stroke>) -> Unit,
      currentBrush: Brush,
      onGetNextBrush: () -> Brush,
      modifier: Modifier = Modifier
    ) {
      val canvasStrokeRenderer = remember { CanvasStrokeRenderer.create() }
    
      Box(modifier = Modifier.fillMaxSize()) {
          // The Canvas for drawing the permanent, dry strokes.
          Canvas(modifier = Modifier.fillMaxSize()) {
              finishedStrokes.forEach { stroke ->
                  canvasStrokeRenderer.draw(
                      stroke = stroke,
                      canvas = this,
                      strokeToScreenTransform = Matrix()
                  )
              }
          }
    
          //The wet ink layer for live drawing.
          // The InProgressStrokes composable for the wet ink layer goes here.
      }
    }