Skip to content

Commit

Permalink
Add progress modifier animation with progress percent
Browse files Browse the repository at this point in the history
  • Loading branch information
Ali Nasrabadi committed Apr 6, 2023
1 parent e70037a commit db6fafd
Showing 1 changed file with 51 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.nasrabadiam.progress_modifier

import androidx.annotation.FloatRange
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
Expand Down Expand Up @@ -27,7 +28,7 @@ fun Modifier.progressAnimation(
finishedListener: (() -> Unit)? = null
): Modifier = composed(
inspectorInfo = debugInspectorInfo {
name = "cancelableProgress"
name = "progressAnimation"
properties["durationMillis"] = durationMillis
properties["progressColor"] = progressColor
properties["finishedListener"] = finishedListener
Expand All @@ -48,6 +49,55 @@ fun Modifier.progressAnimation(
drawWithContent {
widthValue = size.width

drawContent()
inset(
left = 0.0f,
top = 0.0f,
right = this.size.width - size.width,
bottom = this.size.height - size.height
) {
drawIntoCanvas { canvas ->
val layerRect = Rect(Offset.Zero, Size(widthAnimation, size.height))
canvas.drawRect(layerRect, paint)
}
}
}
}
)

private const val ANIMATION_DURATION_IN_MILLIS = 300
fun Modifier.progressAnimation(
@FloatRange(0.0, 100.0) percent: Float,
progressColor: Color = Color.Black,
): Modifier = composed(
inspectorInfo = debugInspectorInfo {
name = "progressAnimation"
properties["percent"] = percent
properties["progressColor"] = progressColor
},
factory = {
val percentValue = if (percent > 100) {
100f
} else if (percent < 0) {
0f
} else {
percent
}
val paint = Paint().apply {
color = progressColor
alpha = PROGRESS_ALPHA_VALUE
}
var maxWidth by remember { mutableStateOf(0f) }

val widthValue = maxWidth * percentValue / 100
val widthAnimation by animateFloatAsState(
targetValue = widthValue,
animationSpec = tween(ANIMATION_DURATION_IN_MILLIS, easing = LinearEasing),
)

drawWithContent {
maxWidth = size.width

drawContent()
inset(
left = 0.0f,
Expand Down

0 comments on commit db6fafd

Please sign in to comment.