Skip to content

Instantly share code, notes, and snippets.

@belinwu
Forked from vishal2376/SweepGradientImage.kt
Created May 27, 2024 09:37
Show Gist options
  • Save belinwu/2d13542cf170f041c269319dbf1c2ab1 to your computer and use it in GitHub Desktop.
Save belinwu/2d13542cf170f041c269319dbf1c2ab1 to your computer and use it in GitHub Desktop.

Revisions

  1. @vishal2376 vishal2376 created this gist May 25, 2024.
    81 changes: 81 additions & 0 deletions SweepGradientImage.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,81 @@
    @Composable
    fun SweepGradientImage(
    imgResId: Int,
    maxImgSize: Dp = 250.dp,
    maxImgRotation: Float = -10f
    ) {

    var animationPlayed by remember { mutableStateOf(false) }

    val lineOffset by animateFloatAsState(
    targetValue = if (animationPlayed) 1f else -1.0f,
    animationSpec = tween(500),
    label = "",
    )

    val imgAlpha by animateFloatAsState(
    targetValue = if (animationPlayed) 1f else 0.5f,
    animationSpec = tween(300),
    label = "",
    )

    val imgSize by animateDpAsState(
    targetValue = if (animationPlayed) maxImgSize else maxImgSize - 100.dp,
    animationSpec = spring(
    dampingRatio = Spring.DampingRatioMediumBouncy,
    stiffness = Spring.StiffnessLow
    ), label = ""
    )

    val imgRotation by animateFloatAsState(
    targetValue = if (animationPlayed) maxImgRotation - 20f else maxImgRotation,
    animationSpec = spring(
    dampingRatio = Spring.DampingRatioMediumBouncy,
    stiffness = Spring.StiffnessLow
    ), label = ""
    )

    Box(
    modifier = Modifier
    .size(imgSize)
    .graphicsLayer { rotationZ = imgRotation }
    .clip(RoundedCornerShape(16.dp))
    .clickable { animationPlayed = !animationPlayed }
    ) {
    Image(
    painter = painterResource(id = imgResId),
    contentDescription = null,
    contentScale = ContentScale.Crop,
    modifier = Modifier
    .drawWithCache {
    val lineWidth = 200

    val startOffset = Offset(size.width * lineOffset, size.height * lineOffset)
    val endOffset =
    Offset(startOffset.x.plus(lineWidth), startOffset.y.plus(lineWidth))

    val gradient = Brush.linearGradient(
    colors = listOf(
    Color.Transparent,
    Color.White.copy(0.9f),
    Color.Transparent
    ),
    start = startOffset,
    end = endOffset
    )

    onDrawWithContent {
    drawContent()
    drawRect(
    gradient,
    topLeft = Offset.Zero,
    size = size
    )
    }
    }
    .graphicsLayer {
    alpha = imgAlpha
    }
    )
    }
    }