Share
Embed
Interacting with Composable Canvas
Making a custom view using Android Canvas is associated with a big challenge. After all, it is this scary and complicated math that controls everything, and we usually want to reach for simpler solutions. In this session, we will learn how to create a beautiful, animated, and interactive bar chart using a jetpack compose canvas. I will guide you through the scary math and try to convince you there is nothing to be scared about. With jetpack compose, UI is easier to write and test, even the canvas.
Piotr Prus
November 07, 2022
Transcript
109 slides
-
Interact with @Composable Canvas Piotr Prus Mobile Tech Lead @Airly
GDG 3City Organizer -
• Android Canvas recap • Composable Canvas • Key di
ff erences • Implementation • Interaction • Animation • State management • Test composable Agenda: -
Canvas draw functions • drawRect() • drawOval() • drawLine() •
drawText() • drawBitmap() • drawPath() -
Canvas draw functions • drawRect() • drawOval() • drawLine() •
drawText() • drawBitmap() • drawPath() -
Canvas draw functions • drawRect() • drawOval() • drawLine() •
drawText() • drawBitmap() • drawPath() -
Composable Canvas @Composable fun Canvas(modifier: Modifier, onDraw: DrawScope.() -> Unit)
= Spacer(modifier.drawBehind(onDraw)) @Composable fun MyCanvas() { Box(modifier = Modifier .size(100.dp) .background(color = Color.White) .drawBehind { drawRect(color = Color.Blue, size = Size(width = 20f, height = 20f)) }) } -
Composable Canvas @Composable fun MyCanvas() { Box(modifier = Modifier .size(100.dp)
.background(color = Color.White) .drawBehind { drawRect(color = Color.Blue, size = Size(width = 20f, height = 20f)) }) } Result: -
Composable Canvas Result: @Composable fun MyCanvas() { Box(modifier = Modifier
.background(color = Color.White) .drawBehind { drawRect(color = Color.Blue, size = Size(width = 20f, height = 20f)) } ) } -
Composable Canvas @Composable fun MyCanvas() { Box(modifier = Modifier .background(color
= Color.White) .drawBehind { drawRect(color = Color.Blue, size = Size(width = 20f, height = 20f)) } ) } You MUST specify size with modi fi er, whether with exact sizes via Modi fi er.size modi fi er, or relative to parent, via Modi fi er. fi llMaxSize, ColumnScope.weight, etc. If parent wraps this child, only exact sizes must be speci fi ed. -
Composable Canvas @Composable fun MyCanvas() { Box(modifier = Modifier .size(100.dp)
.background(color = Color.White) .drawBehind { drawRect(color = Color.Blue, size = Size(width = 20f, height = 20f)) } ) { Box( modifier = Modifier .size(20.dp) .background(color = Color.Red) ) } } Result: -
Composable Canvas @Composable fun MyCanvas() { Box(modifier = Modifier .size(100.dp)
.background(color = Color.White) .drawBehind { drawRect(color = Color.Blue, size = Size(width = 20f, height = 20f)) } ) { Box( modifier = Modifier .size(20.dp) .background(color = Color.Red) .align(Alignment.BottomEnd) ) } } Result: -
Android view Canvas vs Composable canvas val density = LocalDensity.current
val horizontalPadding = with(density) { 20.dp.toPx() } fun dp2px(resource: Resources, dp: Int): Int { return TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), resource.getDisplayMetrics()) .toInt() } private fun dpToPixel(dp: Float): Float { val metrics: DisplayMetrics = this.getResources().getDisplayMetrics() return dp * (metrics.densityDpi / 160f) } -
Android view Canvas vs Composable canvas class CustomView(context: Context?, attr:
AttributeSet?) : View(context, attr) { private var width = 0 private var height = 0 fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { this.width = w this.height = h super.onSizeChanged(w, h, oldw, oldh) } fun onDraw(canvas: Canvas) { canvas.drawText("TEST", width / 2, height / 2, paint) } } @Composable fun MyCanvas() { Canvas(modifier = Modifier, onDraw = { val width = size.width val height = size.height }) } -
@Composable Canvas has no function drawText 😞 android.graphics.Canvas has function
drawText 🙂 Canvas() { this.drawContext.canvas.nativeCanvas.drawText( “Text on canvas”, drawPadding + index.times(distance), size.height, textPaint ) } } val textPaint = Paint().apply { color = MaterialTheme.colors.onPrimary.toArgb() textAlign = Paint.Align.CENTER this.textSize = textSize typeface = Typeface.DEFAULT_BOLD } -
@Composable fun BarChartCanvas(list: List<Int>, barSelected: (Int) -> Unit) { Row(Modifier
.fillMaxWidth() .padding(12.dp) .height(150.dp) .horizontalScroll(rememberScrollState()) ) { val density = LocalDensity.current val horizontalPadding = with(density) { 12.dp.toPx() } val distance = with(density) { 26.dp.toPx() } val calculatedWidth = with(density) { (distance.times(list.size) + horizontalPadding.times(2)).toDp() } } } -
@Composable fun BarChartCanvas(list: List<Int>, barSelected: (Int) -> Unit) { Row(Modifier
.fillMaxWidth() .padding(12.dp) .height(150.dp) .horizontalScroll(rememberScrollState()) ) { val density = LocalDensity.current val horizontalPadding = with(density) { 12.dp.toPx() } val distance = with(density) { 26.dp.toPx() } val calculatedWidth = with(density) { (distance.times(list.size) + horizontalPadding.times(2)).toDp() } } } -
@Composable fun BarChartCanvas(list: List<Int>, barSelected: (Int) -> Unit) { Row(Modifier
.fillMaxWidth() .padding(12.dp) .height(150.dp) .horizontalScroll(rememberScrollState()) ) { val density = LocalDensity.current val horizontalPadding = with(density) { 12.dp.toPx() } val distance = with(density) { 26.dp.toPx() } val calculatedWidth = with(density) { (distance.times(list.size) + horizontalPadding.times(2)).toDp() } } } -
@Composable fun BarChartCanvas(list: List<Int>, barSelected: (Int) -> Unit) { Row(Modifier
.fillMaxWidth() .padding(12.dp) .height(150.dp) .horizontalScroll(rememberScrollState()) ) { val density = LocalDensity.current val horizontalPadding = with(density) { 12.dp.toPx() } val distance = with(density) { 26.dp.toPx() } val calculatedWidth = with(density) { (distance.times(list.size) + horizontalPadding.times(2)).toDp() } } } -
@Composable fun BarChartCanvas(list: List<Int>, barSelected: (Int) -> Unit) { Row(Modifier
.fillMaxWidth() .padding(12.dp) .height(150.dp) .horizontalScroll(rememberScrollState()) ) { val density = LocalDensity.current val horizontalPadding = with(density) { 12.dp.toPx() } val distance = with(density) { 26.dp.toPx() } val calculatedWidth = with(density) { (distance.times(list.size) + horizontalPadding.times(2)).toDp() } } } -
@Composable fun BarChartCanvas(list: List<Int>, barSelected: (Int) -> Unit) { Row(Modifier)
{ . . . Canvas( modifier = Modifier .fillMaxHeight() .width(calculatedWidth)){ // Draw functions go here } } -
// Draw scope val lineDistance = size.height.minus(smallPadding.times(2)).div(4) repeat(5) { drawLine(
color = Color.Gray, start = Offset(0f, smallPadding.plus(it.times(lineDistance))), end = Offset(size.width, smallPadding.plus(it.times(lineDistance))) ) } -
// Draw scope val lineDistance = size.height.minus(smallPadding.times(2)).div(4) repeat(5) { drawLine(
color = Color.Gray, start = Offset(0f, smallPadding.plus(it.times(lineDistance))), end = Offset(size.width, smallPadding.plus(it.times(lineDistance))) ) } -
// Draw scope val lineDistance = size.height.minus(smallPadding.times(2)).div(4) repeat(5) { drawLine(
color = Color.Gray, start = Offset(0f, smallPadding.plus(it.times(lineDistance))), end = Offset(size.width, smallPadding.plus(it.times(lineDistance))) ) } -
// Draw scope val lineDistance = size.height.minus(smallPadding.times(2)).div(4) repeat(5) { drawLine(
color = Color.Gray, start = Offset(0f, smallPadding.plus(it.times(lineDistance))), end = Offset(size.width, smallPadding.plus(it.times(lineDistance))) ) } -
// Draw scope val lineDistance = size.height.minus(smallPadding.times(2)).div(4) repeat(5) { drawLine(
color = Color.Gray, start = Offset(0f, smallPadding.plus(it.times(lineDistance))), end = Offset(size.width, smallPadding.plus(it.times(lineDistance))) ) } -
barAreas.forEachIndexed { index, item -> val barHeight = item.value.times(scale).toFloat() drawRoundRect(
color = skyBlue400, topLeft = Offset( x = horizontalPadding + distance.times(index) - barWidth.div(2), y = size.height - barHeight - smallPadding ), size = Size(barWidth, barHeight), cornerRadius = CornerRadius(cornerRadius) ) } -
barAreas.forEachIndexed { index, item -> val barHeight = item.value.times(scale).toFloat() drawRoundRect(
color = skyBlue400, topLeft = Offset( x = horizontalPadding + distance.times(index) - barWidth.div(2), y = size.height - barHeight - smallPadding ), size = Size(barWidth, barHeight), cornerRadius = CornerRadius(cornerRadius) ) } data class BarArea( val index: Int, val xStart: Float, val xEnd: Float, val value: Int ) -
barAreas.forEachIndexed { index, item -> val barHeight = item.value.times(scale).toFloat() drawRoundRect(
color = skyBlue400, topLeft = Offset( x = horizontalPadding + distance.times(index) - barWidth.div(2), y = size.height - barHeight - smallPadding ), size = Size(barWidth, barHeight), cornerRadius = CornerRadius(cornerRadius) ) } data class BarArea( val index: Int, val xStart: Float, val xEnd: Float, val value: Int ) val barAreas = list.mapIndexed { index, i -> BarArea( index = index, value = i, xStart = horizontalPadding + distance.times(index) - distance.div(2), xEnd = horizontalPadding + distance.times(index) + distance.div(2) ) } -
barAreas.forEachIndexed { index, item -> val barHeight = item.value.times(scale).toFloat() drawRoundRect(
color = skyBlue400, topLeft = Offset( x = horizontalPadding + distance.times(index) - barWidth.div(2), y = size.height - barHeight - smallPadding ), size = Size(barWidth, barHeight), cornerRadius = CornerRadius(cornerRadius) ) } -
barAreas.forEachIndexed { index, item -> val barHeight = item.value.times(scale).toFloat() drawRoundRect(
color = skyBlue400, topLeft = Offset( x = horizontalPadding + distance.times(index) - barWidth.div(2), y = size.height - barHeight - smallPadding ), size = Size(barWidth, barHeight), cornerRadius = CornerRadius(cornerRadius) ) } -
barAreas.forEachIndexed { index, item -> val barHeight = item.value.times(scale).toFloat() drawRoundRect(
color = skyBlue400, topLeft = Offset( x = horizontalPadding + distance.times(index) - barWidth.div(2), y = size.height - barHeight - smallPadding ), size = Size(barWidth, barHeight), cornerRadius = CornerRadius(cornerRadius) ) } -
barAreas.forEachIndexed { index, item -> val barHeight = item.value.times(scale).toFloat() drawRoundRect(
color = skyBlue400, topLeft = Offset( x = horizontalPadding + distance.times(index) - barWidth.div(2), y = size.height - barHeight - smallPadding ), size = Size(barWidth, barHeight), cornerRadius = CornerRadius(cornerRadius) ) } -
barAreas.forEachIndexed { index, item -> val barHeight = item.value.times(scale).toFloat() drawRoundRect(
color = skyBlue400, topLeft = Offset( x = horizontalPadding + distance.times(index) - barWidth.div(2), y = size.height - barHeight - smallPadding ), size = Size(barWidth, barHeight), cornerRadius = CornerRadius(cornerRadius) ) } -
barAreas.forEachIndexed { index, item -> val barHeight = item.value.times(scale).toFloat() drawRoundRect(
color = skyBlue400, topLeft = Offset( x = horizontalPadding + distance.times(index) - barWidth.div(2), y = size.height - barHeight - smallPadding ), size = Size(barWidth, barHeight), cornerRadius = CornerRadius(cornerRadius) ) } -
barAreas.forEachIndexed { index, item -> val barHeight = item.value.times(scale).toFloat() drawRoundRect(
color = skyBlue400, topLeft = Offset( x = horizontalPadding + distance.times(index) - barWidth.div(2), y = size.height - barHeight - smallPadding ), size = Size(barWidth, barHeight), cornerRadius = CornerRadius(cornerRadius) ) } -
barAreas.forEachIndexed { index, item -> . . . this.drawIntoCanvas {
canvas -> val textPositionY = chartAreaBottom - barHeight - smallPadding canvas.nativeCanvas.drawText( "${item.value}", horizontalPadding + distance.times(index), textPositionY, paint ) } } -
barAreas.forEachIndexed { index, item -> . . . this.drawIntoCanvas {
canvas -> val textPositionY = chartAreaBottom - barHeight - smallPadding canvas.nativeCanvas.drawText( "${item.value}", horizontalPadding + distance.times(index), textPositionY, paint ) } } -
barAreas.forEachIndexed { index, item -> . . . this.drawIntoCanvas {
canvas -> val textPositionY = chartAreaBottom - barHeight - smallPadding canvas.nativeCanvas.drawText( "${item.value}", horizontalPadding + distance.times(index), textPositionY, paint ) } } -
barAreas.forEachIndexed { index, item -> . . . this.drawIntoCanvas {
canvas -> val textPositionY = chartAreaBottom - barHeight - smallPadding canvas.nativeCanvas.drawText( "${item.value}", horizontalPadding + distance.times(index), textPositionY, paint ) } } val textSize = with(density) { 10.sp.toPx() } val paint = Paint().apply { color = 0xffff47586B.toInt() textAlign = Paint.Align.CENTER this.textSize = textSize } -
fun Modifier.pointerInput( key1: Any?, block: suspend PointerInputScope.() -> Unit ):
Modifier = composed() { val density = LocalDensity.current val viewConfiguration = LocalViewConfiguration.current remember(density) { SuspendingPointerInputFilter(viewConfiguration, density) }.apply { LaunchedEffect(this, key1) { block() } } } Pointer input -
@Composable fun Modifier.startGesture( onStart: (offsetX: Float) -> Unit ): Modifier
{ val interactionSource = remember { MutableInteractionSource() } return this.pointerInput(interactionSource) { forEachGesture { coroutineScope { awaitPointerEventScope { val touch = awaitFirstDown().also { it.consumeDownChange() } onStart(touch.position.x) } } } } } Pointer input -
@Composable fun Modifier.startGesture( onStart: (offsetX: Float) -> Unit ): Modifier
{ val interactionSource = remember { MutableInteractionSource() } return this.pointerInput(interactionSource) { forEachGesture { coroutineScope { awaitPointerEventScope { val touch = awaitFirstDown().also { it.consumeDownChange() } onStart(touch.position.x) } } } } } Pointer input -
@Composable fun Modifier.startGesture( onStart: (offsetX: Float) -> Unit ): Modifier
{ val interactionSource = remember { MutableInteractionSource() } return this.pointerInput(interactionSource) { forEachGesture { coroutineScope { awaitPointerEventScope { val touch = awaitFirstDown().also { it.consumeDownChange() } onStart(touch.position.x) } } } } } Pointer input -
@Composable fun Modifier.startGesture( onStart: (offsetX: Float) -> Unit ): Modifier
{ val interactionSource = remember { MutableInteractionSource() } return this.pointerInput(interactionSource) { forEachGesture { coroutineScope { awaitPointerEventScope { val touch = awaitFirstDown().also { it.consumeDownChange() } onStart(touch.position.x) } } } } } Pointer input -
@Composable fun Modifier.startGesture( onStart: (offsetX: Float) -> Unit ): Modifier
{ val interactionSource = remember { MutableInteractionSource() } return this.pointerInput(interactionSource) { forEachGesture { coroutineScope { awaitPointerEventScope { val touch = awaitFirstDown().also { it.consumeDownChange() } onStart(touch.position.x) } } } } } Pointer input -
@Composable fun Modifier.startGesture( onStart: (offsetX: Float) -> Unit ): Modifier
{ val interactionSource = remember { MutableInteractionSource() } return this.pointerInput(interactionSource) { forEachGesture { coroutineScope { awaitPointerEventScope { val touch = awaitFirstDown().also { it.consumeDownChange() } onStart(touch.position.x) } } } } } Pointer input -
@Composable fun Modifier.startGesture( onStart: (offsetX: Float) -> Unit ): Modifier
{ val interactionSource = remember { MutableInteractionSource() } return this.pointerInput(interactionSource) { forEachGesture { coroutineScope { awaitPointerEventScope { val touch = awaitFirstDown().also { it.consumeDownChange() } onStart(touch.position.x) } } } } } Pointer input -
@Composable fun Modifier.tapOrPress( onStart: (offsetX: Float) -> Unit, onCancel: (offsetX:
Float) -> Unit, onCompleted: (offsetX: Float) -> Unit ): Modifier { val interactionSource = remember { MutableInteractionSource() } return this.pointerInput(interactionSource) { forEachGesture { coroutineScope { awaitPointerEventScope { val tap = awaitFirstDown().also { it.consumeDownChange() } onStart(tap.position.x) val up = waitForUpOrCancellation() if (up == null) { onCancel(tap.position.x) } else { up.consumeDownChange() onCompleted(tap.position.x) } } } } } } Pointer input -
@Composable fun Modifier.tapOrPress( onStart: (offsetX: Float) -> Unit, onCancel: (offsetX:
Float) -> Unit, onCompleted: (offsetX: Float) -> Unit ): Modifier { val interactionSource = remember { MutableInteractionSource() } return this.pointerInput(interactionSource) { forEachGesture { coroutineScope { awaitPointerEventScope { val tap = awaitFirstDown().also { it.consumeDownChange() } onStart(tap.position.x) val up = waitForUpOrCancellation() if (up == null) { onCancel(tap.position.x) } else { up.consumeDownChange() onCompleted(tap.position.x) } } } } } } Pointer input -
@Composable fun Modifier.tapOrPress( onStart: (offsetX: Float) -> Unit, onCancel: (offsetX:
Float) -> Unit, onCompleted: (offsetX: Float) -> Unit ): Modifier { val interactionSource = remember { MutableInteractionSource() } return this.pointerInput(interactionSource) { forEachGesture { coroutineScope { awaitPointerEventScope { val tap = awaitFirstDown().also { it.consumeDownChange() } onStart(tap.position.x) val up = waitForUpOrCancellation() if (up == null) { onCancel(tap.position.x) } else { up.consumeDownChange() onCompleted(tap.position.x) } } } } } } Pointer input -
@Composable fun Modifier.tapOrPress( onStart: (offsetX: Float) -> Unit, onCancel: (offsetX:
Float) -> Unit, onCompleted: (offsetX: Float) -> Unit ): Modifier { val interactionSource = remember { MutableInteractionSource() } return this.pointerInput(interactionSource) { forEachGesture { coroutineScope { awaitPointerEventScope { val tap = awaitFirstDown().also { it.consumeDownChange() } onStart(tap.position.x) val up = waitForUpOrCancellation() if (up == null) { onCancel(tap.position.x) } else { up.consumeDownChange() onCompleted(tap.position.x) } } } } } } Pointer input -
@Composable fun Modifier.tapOrPress( onStart: (offsetX: Float) -> Unit, onCancel: (offsetX:
Float) -> Unit, onCompleted: (offsetX: Float) -> Unit ): Modifier { val interactionSource = remember { MutableInteractionSource() } return this.pointerInput(interactionSource) { forEachGesture { coroutineScope { awaitPointerEventScope { val tap = awaitFirstDown().also { it.consumeDownChange() } onStart(tap.position.x) val up = waitForUpOrCancellation() if (up == null) { onCancel(tap.position.x) } else { up.consumeDownChange() onCompleted(tap.position.x) } } } } } } Pointer input -
Simple selection var selectedPosition by remember { mutableStateOf(0) } val
selectedBar by remember(selectedPosition, barAreas) { derivedStateOf { barAreas.find { it.xStart < selectedPosition && selectedPosition < it.xEnd } } } Modifier.tapOrPress( onStart = { }, onCancel = { }, onCompleted = { selectedPosition = it } ) -
Stateful Simple selection var selectedPosition by remember { mutableStateOf(0) }
val selectedBar by remember(selectedPosition, barAreas) { derivedStateOf { barAreas.find { it.xStart < selectedPosition && selectedPosition < it.xEnd } } } Modifier.tapOrPress( onStart = { }, onCancel = { }, onCompleted = { selectedPosition = it } ) -
Simple selection // in Draw scope if (selectedBar != null)
{ drawRoundRect( brush = Brush.verticalGradient( listOf( skyBlue400.copy(alpha = 0.3f), Color.Transparent ) ), topLeft = Offset( x = horizontalPaddingPx + distancePx.times(bar.index) - areaWidthPx.div(2), y = areaHeightPx.plus(topPaddingPx) - areaHeightPx ), size = Size(areaWidthPx, areaHeightPx), cornerRadius = CornerRadius(cornerRadiusPx) ) } -
Simple selection // in Draw scope if (selectedBar != null)
{ drawRoundRect( brush = Brush.verticalGradient( listOf( skyBlue400.copy(alpha = 0.3f), Color.Transparent ) ), topLeft = Offset( x = horizontalPaddingPx + distancePx.times(bar.index) - areaWidthPx.div(2), y = areaHeightPx.plus(topPaddingPx) - areaHeightPx ), size = Size(areaWidthPx, areaHeightPx), cornerRadius = CornerRadius(cornerRadiusPx) ) } -
Simple selection // in Draw scope if (selectedBar != null)
{ drawRoundRect( brush = Brush.verticalGradient( listOf( skyBlue400.copy(alpha = 0.3f), Color.Transparent ) ), topLeft = Offset( x = horizontalPaddingPx + distancePx.times(bar.index) - areaWidthPx.div(2), y = areaHeightPx.plus(topPaddingPx) - areaHeightPx ), size = Size(areaWidthPx, areaHeightPx), cornerRadius = CornerRadius(cornerRadiusPx) ) } -
Simple selection // in Draw scope if (selectedBar != null)
{ drawRoundRect( brush = Brush.verticalGradient( listOf( skyBlue400.copy(alpha = 0.3f), Color.Transparent ) ), topLeft = Offset( x = horizontalPaddingPx + distancePx.times(bar.index) - areaWidthPx.div(2), y = areaHeightPx.plus(topPaddingPx) - areaHeightPx ), size = Size(areaWidthPx, areaHeightPx), cornerRadius = CornerRadius(cornerRadiusPx) ) } -
Simple selection // in Draw scope if (selectedBar != null)
{ drawRoundRect( brush = Brush.verticalGradient( listOf( skyBlue400.copy(alpha = 0.3f), Color.Transparent ) ), topLeft = Offset( x = horizontalPaddingPx + distancePx.times(bar.index) - areaWidthPx.div(2), y = areaHeightPx.plus(topPaddingPx) - areaHeightPx ), size = Size(areaWidthPx, areaHeightPx), cornerRadius = CornerRadius(cornerRadiusPx) ) } -
Simple selection // in Draw scope if (selectedBar != null)
{ drawRoundRect( brush = Brush.verticalGradient( listOf( skyBlue400.copy(alpha = 0.3f), Color.Transparent ) ), topLeft = Offset( x = horizontalPaddingPx + distancePx.times(bar.index) - areaWidthPx.div(2), y = areaHeightPx.plus(topPaddingPx) - areaHeightPx ), size = Size(areaWidthPx, areaHeightPx), cornerRadius = CornerRadius(cornerRadiusPx) ) } -
Animatable val animatable = remember { Animatable(0f) } ... //Modifier.tapOrPress
onCompleted = { scope.launch { selectedPosition = it animatable.animateTo(1f) } } ... // draw scope drawRoundRect( brush = brush, topLeft = Offset( x = horizontalPadding + distance.times(selectedBar!!.index) - selectionWidth.div(2), y = chartAreaHeight - chartAreaHeight.times(animatable.value)), // use of animatable value size = Size(selectionWidth, chartAreaHeight), cornerRadius = CornerRadius(cornerRadius) ) -
Animatable val animatable = remember { Animatable(0f) } ... //Modifier.tapOrPress
onCompleted = { scope.launch { selectedPosition = it animatable.animateTo(1f) } } ... // draw scope drawRoundRect( brush = brush, topLeft = Offset( x = horizontalPadding + distance.times(selectedBar!!.index) - selectionWidth.div(2), y = chartAreaHeight - chartAreaHeight.times(animatable.value)), // use of animatable value size = Size(selectionWidth, chartAreaHeight), cornerRadius = CornerRadius(cornerRadius) ) -
gestureStarted() tempSelection = xPosition tempAnimatable.animateTo(1) var selectedPosition by remember {
mutableStateOf(0f) } var tempPosition by remember { mutableStateOf(-Int.MAX_VALUE.toFloat()) } val animatable = remember { Animatable(1f) } val tempAnimatable = remember { Animatable(0f) } -
gestureStarted() tempSelection = xPosition tempAnimatable.animateTo(1) var selectedPosition by remember {
mutableStateOf(0f) } var tempPosition by remember { mutableStateOf(-Int.MAX_VALUE.toFloat()) } val animatable = remember { Animatable(1f) } val tempAnimatable = remember { Animatable(0f) } gestureCanceled() tempSelection = -1 tempAnimatable.animateTo(0) -
gestureStarted() tempSelection = xPosition tempAnimatable.animateTo(1) var selectedPosition by remember {
mutableStateOf(0f) } var tempPosition by remember { mutableStateOf(-Int.MAX_VALUE.toFloat()) } val animatable = remember { Animatable(1f) } val tempAnimatable = remember { Animatable(0f) } gestureCanceled() tempSelection = -1 tempAnimatable.animateTo(0) gestureCompleted() animatable = tempAnimatable + animateTo(1) tempAnimatable = 0 selection = tempSelection tempSelection = -1 -
Testing @Composable fun BarChartCanvas(list: List<Int>, barSelected: (Int) -> Unit) Row(Modifier
.fillMaxWidth() .padding(12.dp) .height(150.dp) .testTag("BarChart") .horizontalScroll(rememberScrollState()) ) -
Testing @Composable fun BarChartCanvas(list: List<Int>, barSelected: (Int) -> Unit) Row(Modifier
.fillMaxWidth() .padding(12.dp) .height(150.dp) .testTag("BarChart") .horizontalScroll(rememberScrollState()) ) -
Testing @get:Rule val composeTestRule = createComposeRule() @Test fun checkCanvasExistence() {
val list = mutableStateOf(listOf(1, 2, 3, 4, 5, 6, 7, 8)) composeTestRule.setContent { BarChartCanvas(list = list.value, barSelected = { }) } composeTestRule.onNodeWithTag(testTag = "BarChart").assertExists() } -
Testing @Test fun clickOnThirdElementOfList() { val list = mutableStateOf(listOf(1, 2,
3, 4, 5, 6, 7, 8)) val selectedItem = mutableStateOf(list.value.first()) val distance = with(composeTestRule.density) { (12.dp + 20.dp.times(3)).toPx() } composeTestRule.setContent { BarChartCanvas(list = list.value, barSelected = { selectedItem.value = it }) } composeTestRule.onNodeWithTag(testTag = "BarChart") .performGesture { click(position = Offset(distance, 1f)) } assertEquals(3, selectedItem.value) } -
Testing @Test fun clickOnThirdElementOfList() { val list = mutableStateOf(listOf(1, 2,
3, 4, 5, 6, 7, 8)) val selectedItem = mutableStateOf(list.value.first()) val distance = with(composeTestRule.density) { (12.dp + 20.dp.times(3)).toPx() } composeTestRule.setContent { BarChartCanvas(list = list.value, barSelected = { selectedItem.value = it }) } composeTestRule.onNodeWithTag(testTag = "BarChart") .performGesture { click(position = Offset(distance, 1f)) } assertEquals(3, selectedItem.value) } -
Testing @Test fun clickOnThirdElementOfList() { val list = mutableStateOf(listOf(1, 2,
3, 4, 5, 6, 7, 8)) val selectedItem = mutableStateOf(list.value.first()) val distance = with(composeTestRule.density) { (12.dp + 20.dp.times(3)).toPx() } composeTestRule.setContent { BarChartCanvas(list = list.value, barSelected = { selectedItem.value = it }) } composeTestRule.onNodeWithTag(testTag = "BarChart") .performGesture { click(position = Offset(distance, 1f)) } assertEquals(3, selectedItem.value) } -
Testing @Test fun clickOnThirdElementOfList() { val list = mutableStateOf(listOf(1, 2,
3, 4, 5, 6, 7, 8)) val selectedItem = mutableStateOf(list.value.first()) val distance = with(composeTestRule.density) { (12.dp + 20.dp.times(3)).toPx() } composeTestRule.setContent { BarChartCanvas(list = list.value, barSelected = { selectedItem.value = it }) } composeTestRule.onNodeWithTag(testTag = "BarChart") .performGesture { click(position = Offset(distance, 1f)) } assertEquals(3, selectedItem.value) } -
Testing @Test fun clickOnThirdElementOfList() { val list = mutableStateOf(listOf(1, 2,
3, 4, 5, 6, 7, 8)) val selectedItem = mutableStateOf(list.value.first()) val distance = with(composeTestRule.density) { (12.dp + 20.dp.times(3)).toPx() } composeTestRule.setContent { BarChartCanvas(list = list.value, barSelected = { selectedItem.value = it }) } composeTestRule.onNodeWithTag(testTag = "BarChart") .performGesture { click(position = Offset(distance, 1f)) } assertEquals(3, selectedItem.value) } -
Testing @Test fun clickOnThirdElementOfList() { val list = mutableStateOf(listOf(1, 2,
3, 4, 5, 6, 7, 8)) val selectedItem = mutableStateOf(list.value.first()) val distance = with(composeTestRule.density) { (12.dp + 20.dp.times(3)).toPx() } composeTestRule.setContent { BarChartCanvas(list = list.value, barSelected = { selectedItem.value = it }) } composeTestRule.onNodeWithTag(testTag = "BarChart") .performGesture { click(position = Offset(distance, 1f)) } assertEquals(3, selectedItem.value) } -
Testing @Test fun cancelSelectionOfThirdElement() { val list = mutableStateOf(listOf(1, 2,
3, 4, 5, 6, 7, 8)) val selectedItem = mutableStateOf(list.value.first()) val distance = with(composeTestRule.density) { (12.dp + 20.dp.times(3)).toPx() } composeTestRule.setContent { BarChartCanvas(list = list.value, barSelected = { selectedItem.value = it }) } composeTestRule.onNodeWithTag(testTag = "BarChart") .performGesture { down(Offset(distance, 1f)) } .performGesture { moveBy(Offset(distance, 0f)) } .performGesture { up() } assertEquals(1, selectedItem.value) } -
Testing @Test fun cancelSelectionOfThirdElement() { val list = mutableStateOf(listOf(1, 2,
3, 4, 5, 6, 7, 8)) val selectedItem = mutableStateOf(list.value.first()) val distance = with(composeTestRule.density) { (12.dp + 20.dp.times(3)).toPx() } composeTestRule.setContent { BarChartCanvas(list = list.value, barSelected = { selectedItem.value = it }) } composeTestRule.onNodeWithTag(testTag = "BarChart") .performGesture { down(Offset(distance, 1f)) } .performGesture { moveBy(Offset(distance, 0f)) } .performGesture { up() } assertEquals(1, selectedItem.value) } -
Testing @Test fun cancelSelectionOfThirdElement() { val list = mutableStateOf(listOf(1, 2,
3, 4, 5, 6, 7, 8)) val selectedItem = mutableStateOf(list.value.first()) val distance = with(composeTestRule.density) { (12.dp + 20.dp.times(3)).toPx() } composeTestRule.setContent { BarChartCanvas(list = list.value, barSelected = { selectedItem.value = it }) } composeTestRule.onNodeWithTag(testTag = "BarChart") .performGesture { down(Offset(distance, 1f)) } .performGesture { moveBy(Offset(distance, 0f)) } .performGesture { up() } assertEquals(1, selectedItem.value) } -
Testing @Test fun cancelSelectionOfThirdElement() { val list = mutableStateOf(listOf(1, 2,
3, 4, 5, 6, 7, 8)) val selectedItem = mutableStateOf(list.value.first()) val distance = with(composeTestRule.density) { (12.dp + 20.dp.times(3)).toPx() } composeTestRule.setContent { BarChartCanvas(list = list.value, barSelected = { selectedItem.value = it }) } composeTestRule.onNodeWithTag(testTag = "BarChart") .performGesture { down(Offset(distance, 1f)) } .performGesture { moveBy(Offset(distance, 0f)) } .performGesture { up() } assertEquals(1, selectedItem.value) } -
Testing @Test fun cancelSelectionOfThirdElement() { val list = mutableStateOf(listOf(1, 2,
3, 4, 5, 6, 7, 8)) val selectedItem = mutableStateOf(list.value.first()) val distance = with(composeTestRule.density) { (12.dp + 20.dp.times(3)).toPx() } composeTestRule.setContent { BarChartCanvas(list = list.value, barSelected = { selectedItem.value = it }) } composeTestRule.onNodeWithTag(testTag = "BarChart") .performGesture { down(Offset(distance, 1f)) } .performGesture { moveBy(Offset(distance, 0f)) } .performGesture { up() } assertEquals(1, selectedItem.value) } -
Testing @Test fun cancelSelectionOfThirdElement() { val list = mutableStateOf(listOf(1, 2,
3, 4, 5, 6, 7, 8)) val selectedItem = mutableStateOf(list.value.first()) val distance = with(composeTestRule.density) { (12.dp + 20.dp.times(3)).toPx() } composeTestRule.setContent { BarChartCanvas(list = list.value, barSelected = { selectedItem.value = it }) } composeTestRule.onNodeWithTag(testTag = "BarChart") .performGesture { down(Offset(distance, 1f)) } .performGesture { moveBy(Offset(distance, 0f)) } .performGesture { up() } assertEquals(1, selectedItem.value) } -
Testing @Test fun cancelSelectionOfThirdElement() { val list = mutableStateOf(listOf(1, 2,
3, 4, 5, 6, 7, 8)) val selectedItem = mutableStateOf(list.value.first()) val distance = with(composeTestRule.density) { (12.dp + 20.dp.times(3)).toPx() } composeTestRule.setContent { BarChartCanvas(list = list.value, barSelected = { selectedItem.value = it }) } composeTestRule.onNodeWithTag(testTag = "BarChart") .performGesture { down(Offset(distance, 1f)) } .performGesture { moveBy(Offset(distance, 0f)) } .performGesture { up() } assertEquals(1, selectedItem.value) } -
Testing @Test fun cancelSelectionOfThirdElement() { val list = mutableStateOf(listOf(1, 2,
3, 4, 5, 6, 7, 8)) val selectedItem = mutableStateOf(list.value.first()) val distance = with(composeTestRule.density) { (12.dp + 20.dp.times(3)).toPx() } composeTestRule.setContent { BarChartCanvas(list = list.value, barSelected = { selectedItem.value = it }) } composeTestRule.onNodeWithTag(testTag = "BarChart") .performGesture { down(Offset(distance, 1f)) } .performGesture { moveBy(Offset(distance, 0f)) } .performGesture { up() } assertEquals(1, selectedItem.value) } -
Final thoughts • Drawing using Composable Canvas is very similar
to Android View Canvas • drawText is missing in Compose version • Testing is easy and very readable • Animation has good documentation -
Thanks for listening Piotr Prus Mobile Tech Lead @Airly GDG
3City Organizer