I am trying to add a seekbar on Canvas where blue line is showing in the image blow. When I try to add material component on canvas it says:
@Composable invocations can only happen from the context of a @Composable function
and if I do it in Composable function I do not know how can I get the coordinates of line and draw Seekbar on it.
here is my code:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.myComposable.setContent {
graphPoints(maxOnX = 20f, maOnY = 10, 4.0f,6.0f,0f,0f)
}
}
@Composable
fun graphPoints(maxOnX: Float, maOnY: Int, timeStart: Float, timeEnd: Float,
concentrationStart: Float, concentrationEnd: Float) {
Canvas(modifier = Modifier.fillMaxSize()) {
val canvasWidth = size.width
val canvasHeight = size.height
val unitX: Float = canvasWidth / maxOnX
val nextAfterX: Float = canvasWidth / maxOnX
for (i in 0 until canvasWidth.toInt() step nextAfterX.toInt() * 2) {
if (i == 0) {
continue
}
drawLine(
start = Offset(x = i.toFloat(), y = canvasHeight),
end = Offset(x = i.toFloat(), y = canvasHeight - 10),
color = Color.Black,
strokeWidth = 2F
)
}
val nextAfterY: Float = canvasHeight / maOnY.toFloat()
for (i in 0 until canvasHeight.toInt() step nextAfterY.toInt()) {
if (i == 0) {
continue
}
drawLine(
start = Offset(x = 0f, y = i.toFloat()),
end = Offset(x = 10f, y = i.toFloat()),
color = Color.Black,
strokeWidth = 2F
)
}
drawLine(
start = Offset(x = 0f, y = 0f),
end = Offset(x = 0f, y = canvasHeight),
color = Color.Black,
strokeWidth = 5F
)
drawLine(
start = Offset(x = 0f, y = 0f),
end = Offset(x = 0f, y = canvasHeight),
color = Color.Black,
strokeWidth = 5F
)
drawLine(
start = Offset(x = 0f, y = canvasHeight),
end = Offset(x = canvasWidth, y = canvasHeight),
color = Color.Black,
strokeWidth = 5F
)
if (timeStart > 0 && timeEnd > 0) {
drawCircle(
color = Color.Black,
radius = 10f,
center = Offset(timeStart * unitX, canvasHeight / 2)
)
drawLine(
start = Offset(timeStart * unitX, 0f),
end = Offset(x = timeStart * unitX, y = canvasHeight),
color = Color.Black,
strokeWidth = 2F
)
drawCircle(
color = Color.Black,
radius = 10f,
center = Offset(timeEnd * unitX, canvasHeight - (canvasHeight / 4))
)
drawLine(
start = Offset(timeEnd * unitX, 0f),
end = Offset(x = timeEnd * unitX, y = canvasHeight),
color = Color.Black,
strokeWidth = 2F
)
drawLine(
start = Offset(timeStart * unitX, canvasHeight - (canvasHeight / 2)),
end = Offset(x = timeEnd * unitX, y = canvasHeight - (canvasHeight / 4)),
color = Color.Blue,
strokeWidth = 2F
)
}
}
}
@Preview
@Composable
fun PreviewMessageCard() {
graphPoints(maxOnX = 20f, maOnY = 10, 4.0f,6.0f,0f,0f)
}