Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an icon to canvas in Jetpack Compose?

I am trying to add and icon from resource in Canvas DrawScope. The nearest solution I found is drawImage(), but it doesn't work for my case. Also I cannot use the normal Icon() composable inside the DrawScope. So is there any work around to display an icon inside canvas, similarly to the way we do it with composable:

import androidx.compose.material.Icon

Icon(Icons.Rounded.Menu, contentDescription = "Localized description")
like image 611
Vasil Test Avatar asked Sep 04 '25 17:09

Vasil Test


1 Answers

Drawscope extension for abstract class Painter has size, alpha and colorFilter params. You can change these params. If you wish to change draw position of Icon, it' drawn top left (0,0) by default you can use translate function or other functions such as rotate or scale for further operations

val painter = rememberVectorPainter(Icons.Rounded.Menu)
Canvas(modifier = Modifier.fillMaxSize()) {
    translate(left = 0f, top = 0f) {
        with(painter) {
         //   draw(size = painter.intrinsicSize)
            draw(
                size = Size(40.dp.toPx(), 40.dp.toPx()),
                alpha = 1f,
                colorFilter = ColorFilter.tint(Color.Red)
            )
        }
    }
}
like image 107
Thracian Avatar answered Sep 06 '25 16:09

Thracian