我已经创建了一个进度条,它有一条从某个起点到某个终点的直线。
下图显示了我的进度条的外观:

问题是绘制的线条超出了用于绘制它的画布的宽度。我在上面的图片中将画布的宽度设置为笑脸,但增长的线条超过了它。
此代码用于创建在绘制增长线时使用的LaunchedEffect:
val animatedProgress = remember { Animatable(0.001f) }
val context = LocalContext.current
LaunchedEffect(animatedProgress) {
animatedProgress.animateTo(
1f,
animationSpec = repeatable(
1,
animation = tween(durationMillis = 3000, easing = LinearEasing)
)
)
}绘制静态线的代码:
//Below canvas draws a static line for a certain length
Canvas(modifier = Modifier.constrainAs(staticLineCanvas){
top.linkTo(firstCircle.top)
bottom.linkTo(firstCircle.bottom)
start.linkTo(firstCircle.end)
}){
drawLine(
cap = StrokeCap.Round,
strokeWidth = 4.39.dp.toPx(),
color = bright_green,
start = Offset(0f, 0f),
end = Offset(680f, 0f)
)
}用于绘制增长线的代码:
//Below canvas draws the actual growing line
Canvas(modifier = Modifier
.padding(start = 80.dp) //Padding to draw line from the end of static line
.constrainAs(animatedLineCanvas)
{
top.linkTo(secondCircle.top)
bottom.linkTo(secondCircle.bottom)
start.linkTo(secondCircle.end)
end.linkTo(thirdCircle.start)
width = Dimension.fillToConstraints
}) {
val startingPoint = Offset(0f, 0f)
val endingPoint =
Offset(adaptDimenToMultScreens(100.0f, context) * animatedProgress.value, 0f)
//adaptDimenToMultScreens() is supposed to convert value to fit the current screen size.
drawLine(
cap = StrokeCap.Round,
strokeWidth = 4.39.dp.toPx(),
color = bright_green,
start = startingPoint,
end = endingPoint
)
}"adaptDimenToMultScreens()“应该将值转换为适合当前屏幕大小(这可能不起作用)。
adaptDimenToMultScreens()的代码:
fun adaptDimenToMultScreens(value:Float, context: Context) : Float{
val pixels = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
value,
context.getResources().getDisplayMetrics()
)
return pixels
}如何使增长的线条不超过画布(即仅将其绘制到上图中所示的笑脸)?
发布于 2021-06-10 13:11:44
通过在动画的结束点使用'width of canvas‘乘以animatedProgress来解决。
因此,不是这样:
val endingPoint = Offset(adaptDimenToMultScreens(100.0f, context) * animatedProgress.value, 0f)我做到了:
val endingPoint = Offset(animCanvasWidth * animatedProgress.value, animCanvasHeight/2)计算'animCanvasWidth‘和'animCanvasHeight’为:
Canvas(modifier = Modifier
.constrainAs(animatedLineCanvas)
{
top.linkTo(secondCircle.top)
bottom.linkTo(secondCircle.bottom)
start.linkTo(secondCircle.end)
end.linkTo(thirdCircle.start)
width = Dimension.fillToConstraints
}
.onGloballyPositioned { coordinates ->
animCanvasWidth = coordinates.size.toSize().width
animCanvasHeight = coordinates.size.toSize().height
}
) {
.
.
.
}https://stackoverflow.com/questions/67871537
复制相似问题