Home > Software design >  What is the unit of Canvas's size when I use Compose?
What is the unit of Canvas's size when I use Compose?

Time:08-06

In Code A, I get val width = this.size.width when I use Canvas of Compose.

Could you tell me what the unit of the width? is it px? or is it dp?

Code A

  Box(
        modifier=Modifier.matchParentSize()
    ){           
        Canvas(
            modifier = Modifier                   
        ) {
            
            val width = this.size.width 
        }
    }

CodePudding user response:

Canvas size comes from DrawScope interface which is Size that contains Float properties width and height which is in px.

enter image description here

interface DrawScope : Density {

    /**
     * The current [DrawContext] that contains the dependencies
     * needed to create the drawing environment
     */
    val drawContext: DrawContext

    /**
     * Center of the current bounds of the drawing environment
     */
    val center: Offset
        get() = drawContext.size.center

    /**
     * Provides the dimensions of the current drawing environment
     */
    val size: Size
        get() = drawContext.size

    /**
     * The layout direction of the layout being drawn in.
     */
    val layoutDirection: LayoutDirection

  // draw functions
}

And Canvas is a Spacer with Modifier.drawBehind

@Composable
fun Canvas(modifier: Modifier, onDraw: DrawScope.() -> Unit) =
    Spacer(modifier.drawBehind(onDraw))

because onDraw being a lambda with DrawScope receiver we access DrawScope properties.

  • Related