Reputation: 60271
I have a plotterView that plots from bottom-left (0, height) to top Right.
@Composable
fun PlotterView(modifier: Modifier = Modifier, xPoint: Float, yPoint: Float, heightIndex: Float) {
val path by remember { mutableStateOf(Path().apply { moveTo(0f, height) }) }
val penColor = MaterialTheme.colors.onBackground
Canvas(modifier = modifier) {
path.lineTo(
size.width * xPoint,
size.height * (1 - yPoint/heightIndex)
)
drawPath(
path,
color = penColor,
alpha = 1f,
style = Stroke(2.dp.toPx())
)
}
}
However, the above will error out because it cannot access height
outside of canvas
.
I also cannot put into the content of canvas
this line val path by remember { mutableStateOf(Path().apply { moveTo(0f, height) }) }
as it is drawScope that is not composable.
How can I get the height
, so that I can initialize the path
with 0f, height
properly?
Upvotes: 0
Views: 2608
Reputation: 680
Use BoxWithConstraints to contain your canvas, the use the maxHeight which the BoxWithConstraintsScope provided.
Upvotes: 1
Reputation: 60271
I'm hacking around with
if (path.isEmpty) {
path.moveTo(0f, size.height)
}
in the Canvas. The code as below, and it got what I wanted.
@Composable
fun PlotterView(modifier: Modifier = Modifier, xPoint: Float, yPoint: Float, heightIndex: Float) {
val path by remember { mutableStateOf(Path()) }
val penColor = MaterialTheme.colors.onBackground
Canvas(modifier) {
if (path.isEmpty) {
path.moveTo(0f, size.height)
}
path.lineTo(
size.width * xPoint,
size.height * (1 - yPoint / heightIndex)
)
drawPath(
path,
color = penColor,
alpha = 1f,
style = Stroke(2.dp.toPx())
)
}
}
But it looks lame, as I need to hack to get the height
, and not having it when I set the path
stateVariable
Upvotes: 0